WP_QUERY TAX_QUERY ON ACF POST_OBJECT

时间:2016-11-01 作者:Chin Leung

我有一个自定义的帖子类型Wine, 有一个ACF Field 链接到其他自定义帖子类型Producer 作为post_object 关系在我的Producer中,我有一个名为Region.

现在,我要做的是查询所有的白葡萄酒,其中生产者的区域是x。

以下是我尝试过的:

$args = array(
    \'post_type\' => \'wines\',
    \'posts_per_page\' => 12,
    \'tax_query\' => array(
        array(
            \'taxonomy\' => \'type\',
            \'field\' => \'slug\',
            \'terms\' => \'white\'
        ),
        array(
            \'taxonomy\' => \'region\',
            \'field\' => \'slug\',
            \'terms\' => \'alsace\'
        )
    )
);
我的问题是tax_query 在上执行wine 而不是producer. 我看过WP_Query 而且似乎找不到实现这一目标的例子。

谁能给我指点路吗?谢谢

更新1我已检索到制作人的ID列表,将其添加到meta_query:

$producers = new WP_Query(
    array(
        \'post_type\' => \'producers\',
        \'posts_per_page\' => -1
    )
);

$producersIds = wp_list_pluck($producers, \'ID\');
之后,我更新了$args 通过添加元查询:

\'meta_query\' => array(
    array(
        \'key\' => \'producer\',
        \'value\' => $producerIds,
        \'compare\' => \'IN\'
    )
)

1 个回复
最合适的回答,由SO网友:Chin Leung 整理而成

更新1

正如@Florian指出的,我们不需要使用wp\\u list\\u pulk函数,只需添加\'fields\' => \'ids\' 到WP\\U查询以检索ID列表:

$producers = new WP_Query(
    array(
        \'fields\' => \'ids\',
        \'post_type\' => \'producers\',
        \'posts_per_page\' => -1,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'region\',
                \'field\' => \'slug\',
                \'terms\' => \'alsace\'
            )
        )
    )
);
然后通过替换$producerIds来检索葡萄酒by$制片人->帖子`。

解决方案

首先,我必须从该地区取回生产商:

$producers = new WP_Query(
    array(
        \'post_type\' => \'producers\',
        \'posts_per_page\' => -1,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'region\',
                \'field\' => \'slug\',
                \'terms\' => \'alsace\'
            )
        )
    )
);
然后使用wp_list_pluck:

$producerIds = wp_list_pluck($producers->posts, \'ID\');
最后,我用生产者的ID检索葡萄酒:

$wines = new WP_Query(
    array(
        \'post_type\' => \'wines\',
        \'posts_per_page\' => 12,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'type\',
                \'field\' => \'slug\',
                \'terms\' => \'white\'
            )
        ),
        \'meta_query\' => array(
            array(
                \'key\' => \'producer\',
                \'value\' => $producerIds,
                \'compare\' => \'IN\'
            )
        )
    )
);

相关推荐