将过滤器添加到acf关系字段

问题描述 投票:5回答:1

我正在使用wordpress 4.9.7,我正在使用advanced custom fields 4.4.12

在我的后端,我有一个名为coins的帖子类型,它有一个名为related_coins的关系字段和一个文本字段,称为algorithm。基本上我的关系字段创建了与自定义帖子类型products的关系。所以产品可以与几个硬币有关系。

我目前只能按帖子类型过滤。但是,我想通过帖子类型algorithm的自定义字段coin进行过滤。

enter image description here

我尝试了以下方法:

function graphic_card_products_query( $args, $field, $post_id ) {

    $args['meta_query'] = array(
        array(
        'key' => 'algorithm', // name of custom field
        'value' => 'related_coins',
        'compare' => 'LIKE'
        )
    )

    // return
    return $args;

}

// filter for every field
add_filter('acf/fields/relationship/query/name=related_coins', 'graphic_card_products_query', 10, 3);

基本上我试图得到自定义字段algorithm具有的所有值的列表,并将其作为过滤器选项返回到关系字段related_coin

目前我什么都没收到。

有什么建议我做错了吗?

php wordpress advanced-custom-fields
1个回答
2
投票

我已经使用您的代码作为基础进行了测试,我可以确认它对我有用。我会详细说明我做了什么。

首先,你可能已经发现了它,但是在你的meta_query之后你缺少一个分号。所以我解决了这个问题

$args['meta_query'] = array(
    array(
    'key' => 'algorithm', // name of custom field
    'value' => 'related_coins',
    'compare' => 'LIKE'
    )
); // <-- this one!

接下来,我确保我过滤的字段确实是一个“关系”字段,而不是任何其他“关系”字段类型(例如,Post Object,Links,Taxonomy)。他们有自己的过滤器(ACF Reference: Filters)

最后,我确认meta_query是正确的,也是我所期待的。所以你的meta_query正在寻找具有自定义字段'algorithm'和值'related_coins'的产品。 (这可能是正确的,但要确保你想要的值是'related_coins',因为它听起来像一个键,而不是一个值)。然后,您将使用LIKE运算符,该运算符将值与值中包含的“related_coins”匹配。例如,它将匹配'123_related_coins''related_coins_123',以及'related_coins'。

正如我所说,这可能是你想要的,但只是理解这是元查询的意思。

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.