• Hi
    I have list of posts as: post 1, post 2…post 10.
    When I change the posts order using:

    function my_home_category( $query ) {
    $query->set( 'orderby', 'title' );
    $query->set( 'order', 'ASC' );
    }
    add_action( 'pre_get_posts', 'my_home_category' );

    I get post 10 before post 2 how can I change this?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    1. Please provide a link to a page on your site where we can see this. Thanks.

    2. Is post 10 sticky?

    Thread Starter meravjon

    (@meravjon)

    Hi Steve
    Thanks for reply.
    The site is still on local host.
    Post 10 is not sticky.

    Moderator bcworkz

    (@bcworkz)

    Titles are sorted alphabetically by ASCII order, so numbers are treated as characters, not numerically. So post_10 is alphabetically before post_2. To get numeric ordering in this scenario you must coordinate digit places: post_01, post_02, post_03,…post_10, post_11, etc. If you expect more than 99 posts (and less than 999), use 3 digit places (post_001, etc.)

    Thread Starter meravjon

    (@meravjon)

    Hi bcworkz
    Thanks for reply.
    My site is up and your solution does work. But I don’t like the title with the extar zero.
    Isn’t there any way to apply another sort after the alphabetic to get the numbers right order?
    Here’s the link to a page

    Moderator bcworkz

    (@bcworkz)

    With varchar data like meta data we can append +0 to the ORDER BY column term to get natural sorting, but this trick doesn’t seem to work on plain text fields like titles. On the off chance it would work for you in your situation, it might be worth trying this anyway, as the alternative that will certainly work is far less efficient. Hook the ‘posts_orderby’ filter and return wp_posts.post_title+0 ASC, wp_posts.post_title ASC (assuming your DB table prefix is wp_)

    I think the only reliable approach for text fields is to sort the results post-query using PHP’s usort() combined with the natural string comparison function strnatcmp(). You can do so with the ‘posts_results’ filter, which passes the array of posts the query returned to your callback. Sort as desired and return the result.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘display posts order by title with numbers’ is closed to new replies.