高级自定义字段:无法按自定义字段查询帖子 [英] Advanced custom fields: can't query posts by custom field

查看:41
本文介绍了高级自定义字段:无法按自定义字段查询帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查询 ACF 字段show_on_frontpage"值等于是"的帖子(请参阅下面屏幕截图中该字段的定义).按照

解决方案

根据 ACF 论坛上的这个问题/答案:

https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/

最好将您的复选框字段切换为 True/False 字段,因为看起来您的复选框组字段只包含一个选项.

<块引用>

复选框存储为序列化数据,您将无法使用 WP_Query 按复选框字段进行过滤.

如果您使用真/假字段,那么您可以使用 WP_Query,真/假字段为 0(零)表示假,1 表示真.

因此,如果您将复选框字段切换为 True/False 字段,您将按如下方式重写代码:

$args = 数组('posts_per_page' =>-1,'meta_key' =>'show_on_frontpage','元值' =>1/* 或真 */);$my_posts = new WP_Query($args);如果 ($my_posts->have_posts()) {而 ($my_posts->have_posts()) : $my_posts->the_post();/* 选中复选框的每个帖子的内容都放在这里 */终了;}

I'm trying to query posts whose ACF field "show_on_frontpage" value is equal to "yes" (see definition of this field in screenshot below). As prescribed in ACF docs here's my code:

$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;
}

This returns/displays nothing. If I used instead simply $args = array('posts_per_page' => -1); then I get all my posts and "yes" shows up for those that have "yes" as the value of their "show_on_frontpage" field.

What's wrong with my code?

解决方案

According to this question/answer on the ACF forum:

https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/

It would be better to switch your checkbox field to a True/False field instead, since it appears that your checkbox group field only contains a single option.

Checkboxes are stored as serialized data and you’re not going to be able to use WP_Query to filter by a checkbox field.

If you use a true/false field then you can use WP_Query, the values of a true/false field are 0 (zero) for false and 1 for true.

So if you switched your checkbox field to a True/False field, you would rewrite your code as follows:

$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;
}

这篇关于高级自定义字段:无法按自定义字段查询帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆