基于 ACF 转发器子字段自定义分类法查询帖子

Query posts based on an ACF repeater sub field custom taxomomy

我有一个自定义 post 类型,其中列出了一组颜色以及使用 ACF 中继器时可用的产品类型。

目的是在另一页上列出具有适当可用颜色的 CPT。使用自定义分类法设置颜色的可用性 ('availability')

为了实现这一点,我运行正在使用 WP_Query() 来过滤 post 类型,并且 meta_query。如果我正在查询文本 sub_field,这一切都很好,但我想 运行 对自定义分类法的查询。

根据找到的例子 here 我的代码是这样的:

函数:

function my_posts_where( $where ) {
    $where = str_replace("meta_key = 'colour_swatch_", "meta_key LIKE 'colour_swatch_", $where);
    return $where;
}
add_filter('posts_where', 'my_posts_where');

在我的页面上:

<?php

$args = array(
    'post_type' => 'colourswatch',
    'meta_query' => array(
        array(
            'key' => 'colour_swatch_%_availability',
            'value' => 'windows',
            'compare' => 'LIKE'
        )
    )
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
?>

<p><?php the_title(); ?></p>
<?php
endwhile;
wp_reset_postdata();
?>
不幸的是,

这个 returns 没有返回任何内容,但是如果我将 'availability'(分类法的 sub_field 名称)切换为 'colour_name' 另一个 sub_field 我有这是一个文本字段,并将值更改为 'white' 它 returns 所有以白色为特色的色板 CPT 的列表,所以我知道基础知识是有效的,我想我误解了我需要如何查询分类。这是哪里出了问题?

根据我对分类法的理解,值必须是 ID 而不是名称或 slug 或其他任何东西,因此由于我需要使用名称,所以我需要将其转换为 ID。我发现我可以做到这一点 using get_term_by();

// Get term by name 'windows' in custom taxonomy 'product-types'.
$termId = get_term_by( 'name', 'windows', 'product-types' );

$args = array(
    'post_type' => 'colourswatch',
    'meta_query' => array(
        array(
            'key' => 'colour_swatch_%_availability',
            'value' => $termId->term_id, // translate the term name into its ID
            'compare' => 'LIKE'
        )
    )
);