In this post, I will explain how you can order properly numeric custom post types by title, so the number 10 will be the 10th not the second.
At this point, I assume we already have created the custom post type for our top 10 and I will focus only on the ordering part. In my last article, I have already explained how to create custom post types and improve the back-end interface.

Numeric Custom Post Ordering in Front End and Back End view

First step would be to create the custom post types and give them numbers as titles
Add the following code in active theme’s functions.php file:

 //order numeric posts
 function orderby_post_title_int( $orderby ) { return '(wp_posts.post_title+0) ASC'; }
 //order back-end posts in numeric order
 function set_custom_post_types_admin_order($wp_query) {
   if (is_admin()) {
   // Get the post type from the query
     $post_type = $wp_query->query['post_type'];
   	  if ( $post_type == 'reviews') {
     	add_filter('posts_orderby', 'orderby_post_title_int' );
	  }
   }
 }
 add_filter('pre_get_posts', 'set_custom_post_types_admin_order');

In your theme file (e.g index.php), where you want to display the list with the custom post types, add the code before the loop:
 
Note that our custom post type is called reviews and you need to replace that name with yours.

Final Thoughts

The method uses a filter posts_orderby, which in an unofficial blog it states that is not included in WordPress 3, however I can see that it works; in future major releases it might become deprecated but I don’t see it very likely.
I hope this will help other developers who encountered this issues; let me know if you have any troubles with the code.

3 Responses

  1. Thanks for stopping by, but I prefer to avoid plugins when I can do it within code. That way, we have more flexibility and one less plugin to maintain or fix in case it breaks.

Comments are closed.