根据自定义产品属性值过滤Woocommerce产品

根据自定义产品属性值过滤Woocommerce产品

本文介绍了根据自定义产品属性值过滤Woocommerce产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Woocommerce中,我有一个名为 restriction_id 的产品属性。我想根据某些限制ID 来过滤产品。例如,如果在php会话变量中将值设置为 35 ,我想过滤掉所有将strict_id设置为 35

In Woocommerce, I have a product attribute called restriction_id. I am wanting to filter the products based on certain restriction id's. For example if a value is set to 35 in a php session variable I want to filter out any product that has the attribute for restriction_id set to 35.

我会在这里放什么?

这是我的起始代码:

// Define the woocommerce_product_query callback
function action_woocommerce_product_query( $q, $instance ) {
    // The code
};
// Add the action
add_action( 'woocommerce_product_query', __NAMESPACE__.'\\action_woocommerce_product_query', 10, 2 );

我们将不胜感激。

推荐答案

已更新:尝试使用以下:

Updated: Try the following tax query instead:

add_filter( 'woocommerce_product_query_tax_query', 'custom_product_query_meta_query', 10, 2 );
function custom_product_query_meta_query( $tax_query, $query ) {
    if( is_admin() ) return $tax_query;

    // HERE set the taxonomy of your product attribute (custom taxonomy)
    $taxonomy = 'pa_restriction_id'; // Note: always start with "pa_" in Woocommerce

    // HERE Define your product attribute Terms to be excluded
    $terms = array( '35' ); // Note: can be a 'term_id', 'slug' or 'name'

    // The tax query
    $tax_query[] = array(
        'taxonomy'         => $taxonomy,
        'field'            => 'slug', // can be a 'term_id', 'slug' or 'name'
        'terms'            => $terms,
        'operator'         => 'NOT IN', // Excluded
    );

    return $tax_query;
}

代码进入活动子主题(或活动主题)的function.php文件)。经过测试,可以正常工作。

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于根据自定义产品属性值过滤Woocommerce产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:06