[英]How to sort the result of wp_query
I'm trying to sort the results of wp_query, i want to sort it by different parameters without make the query again. 我正在尝试对wp_query的结果进行排序,我希望通过不同的参数对其进行排序,而无需再次进行查询。 I have something like that:
我有类似的东西:
$the_query = new WP_Query( $args );
And i want to sort $the_query, WP_Query returns a structure like that: 我想要排序$ the_query,WP_Query返回一个这样的结构:
$the_query->posts[0]->title;
So, I want to sort all the elements by 'title' for example. 所以,我想用'title'对所有元素进行排序。 I tried this:
我试过这个:
usort($the_query->posts, function($a, $b) {
return $a['title'] - $b['title'];
});
I want to sort after i do the query. 我想在查询之后进行排序。 Is because i want tosort many times and i dont want to do the query every time i want to sort
是因为我想要多次tosort,我不想每次我想要排序时进行查询
SOLUTION 解
This returns Fatal error: Cannot use object of type WP_Post as array 这将返回致命错误:无法使用WP_Post类型的对象作为数组
usort($the_query->posts, function($a, $b) {
return $a['title'] - $b['title'];
});
This is because the structure of the array is like that: 这是因为数组的结构是这样的:
$the_query->posts[0]->title;
so you have to change $a['title'] - $b['title']
for $a->title - $b->title
and using the answer of Pieter Goosen the Final result is: 所以你必须更改
$a['title'] - $b['title']
$a->title - $b->title
并使用Pieter Goosen的答案,最终结果如下:
usort($the_query->posts, function($a, $b) {
return strcasecmp(
$a->title,
$b->title
);
});
Thank for all 谢谢大家
Look at the orderby
and order
parameters in WP_Query
. 查看
WP_Query
中的orderby
和order
参数。 If you need to sort by post title, you can add the following to your query parameters 如果需要按帖子标题排序,可以将以下内容添加到查询参数中
'orderby' => 'title'
'order' => 'ASC'
EDIT 编辑
If you need to sort with usort
, you can do the following 如果您需要使用
usort
排序,则可以执行以下操作
usort($the_query->posts, function($a, $b) {
return strcasecmp(
$a->post_title,
$b->post_title
);
});
WP_Query('orderby=date&order=DESC') WP_Query( '的OrderBy =日期&顺序DESC =')
Or try this, if you want to sort based on custom meta value. 或者尝试这个,如果你想根据自定义元值进行排序。
$args = array(
'post_type' => 'post',
'meta_key' => 'pb_issue_featured',
'orderby' => 'meta_value',
'order' => 'DESC',
'posts_per_page' => $posts,
'paged' => $paged,
'paged' => 1,
'meta_query' => array(
array(
'key' => 'headline',
'value' => 1,
'compare' => '!='
)
)
);
add_filter( 'posts_orderby', 'filter_query' );
$q = new WP_Query($args);
remove_filter( 'posts_orderby', 'filter_query' );
function filter_query( $query ) {
$query .= ', wp_posts.menu_order ASC';
return $query;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.