Problem ordering posts with numbers for titles numerically E.g. 1, 10, 100

Here’s code that will order posts by the post_title field, numerically. This code will affect the main query for posts on both the back end and front end.

// Apply numeric post ordering for posts in admin and front end.
// Adapted from https://www.fldtrace.com/custom-post-types-numeric-title-order
function wpse247871_post_order( $wp_query ) {
    if ( $wp_query->is_main_query() && $wp_query->query['post_type'] == 'post' ) { 
        add_filter( 'posts_orderby', 'wpse247871_orderby_post_title_int' );
    }  
}  
add_filter('pre_get_posts', 'wpse247871_post_order');

// Cast the post_title field as an integer in SQL.
function wpse247871_orderby_post_title_int( $orderby ) {
    global $wpdb;
    return "({$wpdb->prefix}posts.post_title+0) ASC";
}

Leave a Comment