Numeric Slugs Revisited

|

I like to use numbers in my URLs instead of text because it makes more sense to me. Comic pages go up numerically, and I catalog my illustrations by the custom date number in the lower right corner of the site. However, version 4.3 of WordPress introduced a bit of a snag in that setup. No longer is it possible to have a number as the first element of a clean permalink structure. According to the code itself in wp-includes/post.php:

/*
* Potential date clashes are as follows:
*
* – Any integer in the first permastruct position could be a year.
* – An integer between 1 and 12 that follows ‘year’ conflicts with ‘monthnum’.
* – An integer between 1 and 31 that follows ‘monthnum’ conflicts with ‘day’.
*/

This means that in WordPress 4.3+, the numbers I use to make permalinks will always result in them getting a “-2” appended. Well, that just won’t do.

I wrote about this dilemma back in December (two news posts ago) and figured out the first half of a solution by hacking the core code. Of course, hacking the core code is a really bad idea, so I’ve been tinkering with a plugin or functions.php solution to resolve the issue and I think I’ve come up with a solution.

add_filter('wp_unique_post_slug', 'eljo_unique_post_slug', 1, 6);

function eljo_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
	
	$post = get_post($post_ID);
	if($post_type === 'post'
		&& (
			!$post
				||
			$post->post_name !== $original_slug
		)
		&&
		preg_match('/^[0-9]+$/', $original_slug)
		&&
		$slug_num = intval($original_slug)) {
			
			// don't allow two or four digit integer slugs
			if((preg_match('/^\d{2}$/', $slug_num))
				||
			(preg_match('/^\d{4}$/', $slug_num))) {
			
				return $slug;
			
			}
						
		}
	
	$slug = $original_slug;
	return $slug;

}


Because years in just about every existing calendar system (except perhaps the French Republican) use four digits, and months generally only have two digits, I decided to have WordPress not allow two or four digit slugs. But it will allow any other integer length. That means I can continue to use my three and five digit post slugs and I (hopefully) won’t cause a date conflict for WordPress. This code works on my local dev site with WP 4.4.2.

If you prefer using numbers for your permalink slugs, maybe this is the code you’re looking for.