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

时间:2018-12-06 22:35:11

标签: php wordpress woocommerce product custom-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' );

1 个答案:

答案 0 :(得分:2)

关于分类法,您需要使用税收查询,然后该钩子将有所不同。您还可以针对特定的产品标签进行制作:

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文件中。应该可以。