高级自定义字段:无法通过自定义字段查询帖子
我试图查询ACF字段“show_on_frontpage”值等于“是”(请参阅下面屏幕截图中此字段的定义)的帖子。作为ACF docs规定,这里是我的代码:高级自定义字段:无法通过自定义字段查询帖子
$args = array(
'posts_per_page' => -1,
'meta_key' => 'show_on_frontpage',
'meta_value' => 'yes'
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
if (get_field('show_on_frontpage')) the_field('show_on_frontpage'); ?>
endwhile;
}
这将返回/无显示。如果我简单地使用$args = array('posts_per_page' => -1);
,那么我会得到我所有的帖子,并且对于那些具有“yes”作为其“show_on_frontpage”字段的值的用户,会显示“yes”。
我的代码有什么问题?
根据这个问题上的ACF论坛/回答:
https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/
这将是最好的复选框字段切换到真/假领域,而不是,因为它似乎是你的复选框组领域唯一包含一个选项。
复选框以序列化数据的形式存储,您将无法使用WP_Query通过复选框字段进行过滤。
如果您使用true/false字段,那么您可以使用WP_Query, true/false字段的值为0(零)为false,1为true。
所以,如果你打开你的复选框字段到真/假现场,你可以按如下方式重写代码:
$args = array(
'posts_per_page' => -1,
'meta_key' => 'show_on_frontpage',
'meta_value' => 1 /* or true */
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
/* My content for each post with the checkbox checked goes here */
endwhile;
}
如果使用较新的meta_query => array()
语法这应该工作:
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'show_on_frontpage',
'value' => 'yes',
'compare' => 'LIKE',
)
),
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
echo get_the_title();
// Post stuff
endwhile;
/* Restore original Post Data */
wp_reset_postdata();
}
请注意,您需要给文章ID ACF的辅助功能get_field()
& the_field()
while循环中。
见https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
在更广泛的注意,这条质疑使用post_meta键用于此目的的智慧,是值得一读:https://tomjn.com/2016/12/05/post-meta-abuse/。该文章建议使用自定义分类来实现你所需要的 - 更好的性能。
您的报价代码块2号线缺少一个逗号 - 这只是一个转录错误? – DavidCara
更正,谢谢。这不是问题虽然;) – drake035