0

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

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

为了实现这一点,我正在运行一个过滤帖子类型的 WP_Query() 和一个 meta_query。如果我正在查询文本子字段,这一切都很好,但我想在自定义分类上运行查询。

根据此处找到的示例,我的代码如下所示:

功能:

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();
?>

不幸的是,这没有返回任何结果,但是如果我将“可用性”(分类的子字段名称)切换为“颜色名称”,我拥有的另一个子字段是一个文本字段并将值更改为“白色”,它会返回所有颜色表的列表以白色为特色的 CPT,所以我知道基础知识是有效的,我假设我误解了我需要如何查询分类。这哪里出错了?

4

1 回答 1

0

根据我对分类的理解,该值必须是 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'
        )
    )
);
于 2020-08-27T04:15:50.023 回答