WooCommerce 获取基于特定分类的产品

WooCommerce get products based on specific taxonomy

我需要修改 WooCommerce 产品查询,因为我想根据产品标签自定义分类法过滤商店页面上显示的产品。

所以我在这里尝试过,但它不起作用:

add_filter( 'woocommerce_product_query_meta_query', 'filter', 10, 2 );
function filter( $meta_query, $query ) {
    // Only on category pages
    if ( ! is_product_category() ) {
        return $meta_query;
    }

    $meta_query[] = array(
        'key'     => 'taxonomy',
        'value'   => 'product_tag',
        'compare' => 'EXIST'
    );

    return $meta_query;
}

所以我只想显示其中包含分类法 ABCSD 的所有产品。 代码放在我的functions.php。我在这里做错了什么?

注意事项:

我的意思是我调用这个函数时得到的值:

wp_get_post_terms( $product_id, 'product_tag' );

因为是taxonomy,所以要用tax query,hook会不一样。您也可以为特定的产品标签制作它:

add_filter( 'woocommerce_product_query_tax_query', 'filter_products_with_specific_product_tags', 10, 2 );
function filter_products_with_specific_product_tags( $tax_query, $query ) {
    // Only on category pages
    if ( ! is_product_category() ) 
        return $tax_query;

    $tax_query[] = array(
        'taxonomy' => 'product_tag',
        'field' => 'name',
        'terms' => array('Green', 'Yellow', 'Red'), // Defined product tags term names
    );
    return $tax_query;
};

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该有效。