简体   繁体   中英

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.

Any Help?

据我所知,最好的方法是进行4个单独的查询。

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM