转发器字段的 ACF 查询帖子不为空 [英] ACF Query Posts by Repeater Field Not Empty

查看:29
本文介绍了转发器字段的 ACF 查询帖子不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在网上好像没有答案,可能是因为不可能.我只是想查询转发器字段有行"的所有帖子.即

This question seems to be unanswered on the internet, perhaps because it is not possible. I simply want to query all posts where the repeater field 'has rows'. i.e.

$args = array(
'meta_query'        => array(
'relation' => 'AND',
    array(
        'key'       => 'repeater_field',
        'value'     => '',
        'compare'   => '=!'
    )
);

我知道另一种方法是在循环内运行 if 语句来过滤掉它们,但这与其他一些基于查询中帖子数量的逻辑相混淆.

I know an alternative is to run if statements inside the loop to filter them out, but that messes with some other logic which is based off of the number of posts in the query.

有人对此有任何想法吗?

Does anyone have any thoughts on this?

推荐答案

假设您有一个标记为 My Repeater Field 的中继器字段,并且该中继器至少包含一个字段标记为中继器上的一个字段.

Let's consider you have a Repeater Field labeled My Repeater Field and this repeater contains at least one field labeled A Field on the Repeater.

假设您有默认的 wp_ 表前缀,您需要查看数据库的 wp_postmeta 表以注意转发器上此字段的值与 <代码>meta_key:

Assuming you have the default wp_ table prefix, you need to look at the DB's wp_postmeta table to notice that values for this field on the repeater are stored with the meta_key:

NAME_OF_THE_REPEATER_index_NAME_OF_FIELD_ON_THE_REPEATER

NAME_OF_THE_REPEATER_index_NAME_OF_FIELD_ON_THE_REPEATER

因此,在我们的例子中,如果一个帖子在转发器字段上有 3 行,它的值将存储为:

So, in our case, if a post has 3 rows on the repeater field, its values will be stored as:

my_repeater_field_0_a_field_on_the_repeater
my_repeater_field_1_a_field_on_the_repeater
my_repeater_field_2_a_field_on_the_repeater

知道这一点,如果你想查询转发器上至少有一行的所有帖子,你可以这样做:

Knowing this, if you want to query all posts having at least ONE row on the repeater, you could do:

$meta_query = [
    [
        'key'     => 'my_repeater_field_0_a_field_on_the_repeater',
        'compare' => 'EXISTS',
    ]
];

$args = [
    'posts_per_page'   => -1,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'meta_query'       => $meta_query,
    'post_type'        => 'post',
    'post_status'      => 'publish',
];

$posts_array = get_posts( $args );

注意:WP 文档所述,您只能在 WP >= 3.5 上使用 EXISTS 比较,并且在 WordPress 3.9 及更高版本中使用EXISTS"或NOT EXISTS"比较时无需指定值.我还假设您使用的是 PHP >= 5.4,因此您可以使用短数组语法.如果没有,只需将 [] 替换为 array().

Note: As stated on WP Docs, you can only use the EXISTS comparison on WP >= 3.5 and you don't need to specify a value when using the 'EXISTS' or 'NOT EXISTS' comparisons in WordPress 3.9 and up. I'm also assuming you are using PHP >= 5.4 so you can use short array syntax. If not, just replace [] for array().

这篇关于转发器字段的 ACF 查询帖子不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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