![](/img/trans.png)
[英]Wordpress - category__in is not listing on $wp_query with SEO urls
[英]Wordpress WP_Query category__in with order
嗨,我正在尝试进行查询以获取来自特定类别的帖子,如下所示:
$args = array('category__in' => array(8,3,12,7));
$posts = new WP_Query($args);
但是我需要按照特定的顺序显示帖子(目录ID为8,然后是3,依此类推),我无法使其正常工作,帖子是根据ASC或DESC名称显示的。
有帮助吗?
据我所知,最好的方法是进行4个单独的查询。
您可以按post__in
排序以使用输入值的顺序,但是使用category__in
则是多对多的关系,因此,按我的了解,按order by的使用要困难得多,并且不被支持。 还要注意的是WP_Query()
不返回桩的阵列。
如果您有特定的排序规则集,则可以使用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' );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.