How to achieve numeric URLs in WordPress?

April 11, 2017     Nirmal    

A few days back I came across a strange issue with numeric URLs in WordPress mentioned in support request of WordPress forums that WordPress is adding a suffix whenever we try to make the post/page slug to numeric only.

Suppose, if I have a URL like the following

http://example.com/123456789/

WordPress automatically changes this to

http://example.com/123456789-2/

After checking this weird issue, I thought to debug and find out a solution. After few hours of debugging into WordPress core code, I finally found out a solution to this problem. Here is the final code I came up with to fix this issue.


add_filter( 'wp_unique_post_slug', 'mg_unique_post_slug', 10, 6 );

/**
 * Allow numeric slug
 *
 * @param string $slug The slug returned by wp_unique_post_slug().
 * @param int $post_ID The post ID that the slug belongs to.
 * @param string $post_status The status of post that the slug belongs to.
 * @param string $post_type The post_type of the post.
 * @param int $post_parent Post parent ID.
 * @param string $original_slug The requested slug, may or may not be unique.
 */
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;
}

Hope this helps you if you are having the similar type of issue. Also, if you have any other WordPress related problems/queries then feel free to contact us or create a thread on our Support Forum

Snippets, Wordpress

Leave a Reply