Tech Stuffs

Enabling Numeric Slug on WordPress

One of the filenames on my old PHP site was 101.php, and after moving to WordPress trying to use the slug 101 for it was posing a challenge — it kept on suffixing “-2” automatically no matter what. I looked around for exiting page or post that might be using it already, but when I couldn’t find any I got really confused. ๐Ÿ˜ฎ

Enabling Numeric Slug on WordPress

After some digging, I realised what’s going on — numeric-only slugs are disabled by default, which I wasn’t aware of as I don’t remember needing it before. The reason behind this is that it conflicts with the <!โ€โ€nextpageโ€โ€> tag that lets you to split a single post or page into multiple pages.

To overcome this, I added the following code on my theme’s function.php file, which solved the problem while keeping the pagination functionality intact. Hope it helps you too!

add_filter( 'wp_unique_post_slug', 'mg_unique_post_slug', 10, 6 );
 
function mg_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
 global $wpdb;
 
// Don't change non-numeric values
 if ( ! is_numeric( $original_slug ) || $slug === $original_slug ) {
 return $slug;
 }
 
// Was there any conflict or was a suffix added due to the preg_match() call in wp_unique_post_slug() ?
 $post_name_check = $wpdb->get_var( $wpdb->prepare(
 "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1",
 $original_slug, $post_type, $post_ID, $post_parent
 ) );
 
// There really is a conflict due to an existing page so keep the modified slug
 if ( $post_name_check ) {
 return $slug;
 }
 
// Return our numeric slug
 return $original_slug;
}

Leave a Comment