【问题标题】:Filter Woocommerce products based on custom product attribute value根据自定义产品属性值过滤 Woocommerce 产品
【发布时间】:2018-09-08 09:01:09
【问题描述】:

在 Woocommerce 中,我有一个名为 restriction_id 的产品属性。我想根据某些限制 ID 过滤产品。例如,如果在 php 会话变量中将值设置为 35,我想过滤掉所有将 Restriction_id 属性设置为 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 ); 

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    更新:尝试以下tax query

    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 文件中。经过测试并且可以工作。

    【讨论】:

    • 我无法让这段代码工作。它省略了一切。我还尝试将运算符更改为“IN”,这也省略了所有内容...
    • “restriction_id”是自定义产品属性的名称。我所有的产品都是简单的产品。并非所有产品都可能有自定义的restriction_id。目前我设置了两个产品的restriction_id 为35。我在woocommerce 后端的产品数据属性部分下完成了这项工作
    • 我说的是自定义,因为当我去添加一个属性来添加一个新属性时,它会说“自定义产品属性”,然后是一个添加按钮。当你在测试服务器上尝试时,我会看看我是否可以使用“标签”来让它做我需要的事情
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2016-12-20
    相关资源
    最近更新 更多