你好,我正试图查询从特定类别获取帖子,如:
$args = array('category__in' => array(8,3,12,7));
$posts = new WP_Query($args);
但我需要的帖子显示在那个特定的顺序(猫id 8第一,然后3,等),我不能让它正常工作,根据ASC或DESC名称显示的帖子。
帮忙吗?
您可以按post__in
排序以使用输入值的顺序,但对于category__in
,这是一个多对多的关系,因此使用它排序相当困难,并且据我所知不支持。还需要注意的是,WP_Query()
不返回一个post数组。
如果您有特定的排序规则集,您可以使用category
参数从get_posts()
获取结果,然后使用自定义排序函数使用usort()
和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' );
据我所知,这里最好的方法是进行4个单独的查询。