问题描述
我正在尝试使用 WP_Query 和 meta_query 参数查询帖子:
I'm trying to query posts using WP_Query and meta_query parameters:
$args = array(
'post_type' => 'produkty',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'produkt_aktywny',
'value' => '1',
'compare' => '='),
array(
'key' => 'produkt_dostepnosc',
'value' => '1',
'compare' => '=')
)
);
$query = new WP_Query( $args );
我应该添加什么来按其他两个键('produkt_kategoria' 和 'produkt_cena')对结果进行排序?WP Codex 中没有关于它的内容,但是:
What should I add to order the results by two other keys ('produkt_kategoria' and 'produkt_cena')? There's nothing about it in WP Codex, but this:
"Do you know how to sort the query if the meta_value is an array? Write it here :)"
据此,我相信按多个元值排序是可能的.
According to this, I believe sorting by multiple meta values is possible.
推荐答案
我想显示来自自定义帖子类型的帖子.按自定义字段对其进行排序,并添加一个参数,其中另一个自定义字段为特定值以仅显示选定的帖子.
I wanted to show posts from a custom post type. Order it by a custom field, and add a parameter where an other custom field was a certain value to show only a selection of posts.
例如.选择 custom_posts,其中 custom_field_a=xxxx 并按 custom_field_b 排序
eg. select custom_posts where custom_field_a=xxxx and order by custom_field_b
我花了一段时间才弄明白,在寻找它时,我一直在这个帖子上磕磕绊绊.因此,对于所有遇到相同问题的人,这里是最终解决问题的(简化)代码.
It took me a while to figure it out and when searching for it, I kept on stumbling on this post. So for all people having the same issue, here is the (simplified) code that finally did it.
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'custom_field_b',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'custom_field_a',
'value' => get_post_meta(get_the_ID(),'other_field',true),
'compare' => '='
)
),
);
$loop2 = new WP_Query($args);
您会看到这是一个循环中的循环,因此该值是动态的.当然,这也可以硬编码.
You see that this is a loop in loop and therefor the value is dynamical. Of course, this could be hard coded too.
希望对大家有所帮助!
这篇关于WP_Query - 按多个元值过滤并按其他元值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!