【问题标题】:Advanced custom fields: can't query posts by custom field高级自定义字段:无法按自定义字段查询帖子
【发布时间】:2017-08-26 23:48:37
【问题描述】:

我正在尝试查询 ACF 字段“show_on_frontpage”值等于“yes”的帖子(请参阅下面屏幕截图中此字段的定义)。如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);,那么我会得到我所有的帖子,并且对于那些将“是”作为“show_on_frontpage”字段值的人显示“是”。

我的代码有什么问题?

【问题讨论】:

  • 引用代码块的第 2 行缺少逗号 - 这只是转录错误吗?
  • 已更正,谢谢。但这不是问题;)

标签: advanced-custom-fields


【解决方案1】:

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

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

最好将您的复选框字段切换为 True/False 字段,因为您的复选框组字段似乎只包含一个选项。

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

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

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

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

【讨论】:

  • 感谢@Joe 和很好的发现。它现在有效!只有一件事:在更改字段类型后,字段设置为“true”的帖子没有被查询选中。我必须将它们设置为“false”,更新,然后再次将它们设置为“true”,以便可以选择它们。知道为什么吗?看起来改变一个字段的类型有点搞砸了
  • 我不确定是否有程序化的方法来解决这个问题。当字段类型更改为其他内容时,应用了内容的某些字段类型表现不佳。有时内容会翻译过来,而其他时候,你会遇到这样的情况。希望您在此方法中没有太多页面需要更新。
【解决方案2】:

如果您使用更新的 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();

}

请注意,您需要在 while 循环中将帖子 ID 提供给 ACF 帮助函数 get_field() 和 the_field()。

见https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

在更广泛的意义上,这篇文章质疑为此目的使用 post_meta 键是否明智,值得一读:https://tomjn.com/2016/12/05/post-meta-abuse/。该文章建议使用自定义分类法来实现您的需求 - 提高性能。

【讨论】:

  • 我尝试使用的代码的重点是我没有选择所有帖子,只是为了测试哪些帖子符合标准(浪费资源)。您的 $args 返回所有帖子。
  • 你错了,它只返回“show_on_frontpage”元键设置为“yes”的帖子。我可以理解您的困惑,因此我将修改答案以删除 ACF 条件检查。
  • 对不起!原始代码有一个错误(我遗漏了嵌套数组,并使用了错误的比较运算符)。我已经编辑了答案,它现在应该可以工作了。
猜你喜欢
  • 1970-01-01
  • 2016-06-25
  • 2021-06-29
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2015-09-01
  • 2018-01-29
  • 2021-04-30
相关资源
最近更新 更多