WordPress.org

Forums

How to sort the posts using their post_type (2 posts)

  1. Manoj Trivand
    Member
    Posted 1 year ago #

    I am using two custom post_types where i display both of them in the search page. There i need to sort the posts according to their posttype.

    like if(custom_post_type1)
    {
    print all posts under custom_post_type1;
    }elseif(custom_post_type2)
    {
    print all posts under custom_post_type2;
    }

    I can see that there is query_post , i am not sure about the arguments, specifically i need the post types 1 to be at the first and the other after these posts.

  2. bcworkz
    Member
    Posted 1 year ago #

    None of the usual ways of querying posts will accept post_type as a field to order by in the query. You could use one of the PHP array sort functions to do the sorting once the posts are returned by the query, but it's much more efficient to do this in mySQL than PHP.

    Fortunately, there is a filter that lets you enter your own orderby clause. You would do something like this:

    add_filter('posts_search_orderby', 'mt_type_sort', 10, 2 );
    function mt_type_sort( $clause, $query ) {
       return 'wp_posts.post_type DESC';
    }

    The return value is placed right after the 'ORDERBY' directive in the mySQL query string. Be sure to use the correct table name prefix. I've shown the common "wp_" but yours is quite possibly something else. If the wrong type appears first, simply change "DESC" to "ASC"

    To further sort results of the same type, add more column references separated by commas after the post_type column. For finer control over search results, the original query orderby clause and the current query object are available to the function for further analysis. This code would be placed in functions.php of a child theme or in a simple plugin you could create.

    FYI, query_posts() is a poor choice for customizing queries. The best choice depends on if you want to change the main query or create second query to supplement the main. Use 'pre_get_posts' action for the former andget_posts() for the latter. Since the 'posts_search_orderby' filter directly modifies the search results query, you need not do any more than the above code.

Topic Closed

This topic has been closed to new replies.

About this Topic