WordPress WP_Query category__in with order

Hi I’m trying to make a query to get posts from a specific categories like this:

$args = array('category__in' => array(8,3,12,7));

$posts = new WP_Query($args);

But I need the posts to be displayed in that specific order ( cat id 8 first, then 3, etc ), I can’t get it to work properly, posts are displayed according to ASC or DESC names.

Read More

Any Help?

Related posts

Leave a Reply

2 comments

  1. You can sort by post__in to use the order of the input values, but with category__in it is a many to many relationship, so using it order by is considerably more difficult and is not supported as far as I know. Also note that WP_Query() does not return an array of posts.

    If you have your specific set of ordering rules you can take the results from get_posts() using the category argument, and then use a custom sorting function to order the results using usort() and get_categories().

    // function used by usort() to sort your array of posts
    function sort_posts_by_categories( $a, $b ){
        // $a and $b are post object elements from your array of posts
        $a_cats = get_categories( $a->ID );
        $b_cats = get_categories( $b->ID );
    
        // determine how you want to compare these two arrays of categories...
        // perhaps if the categories are the same you want to follow it by title, etc
    
        // return -1 if you want $a before $b
        // return 1 if you want $b before $a
        // return 0 if they are equal
    }
    
    // get an array of post objects in the 'category' IDs provided
    $posts = get_posts( array( 'category' => '8,3,12,7' ) );
    // sort $posts using your custom function which compares the categories. 
    usort( $posts, 'sort_posts_by_categories' );