嗨,我正在尝试进行查询以获取来自特定类别的帖子,如下所示:
$args = array('category__in' => array(8,3,12,7));
$posts = new WP_Query($args);
但是我需要按照特定的顺序显示帖子(目录号为8,然后是3,依此类推),我无法使其正常工作,帖子是根据ASC或DESC名称显示的。
有帮助吗?
您可以通过排序post__in
来使用输入值的顺序,但是使用category__in
它是多对多的关系,所以据我所知,使用它的排序方式要困难得多,并且不被支持。另请注意,WP_Query()
它不返回帖子数组。
如果您有特定的排序规则集,则可以get_posts()
使用category
参数获取结果,然后使用自定义排序功能使用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' );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句