Filter Woocommerce products based on custom product attribute value

荒凉一梦 提交于 2019-12-11 02:13:28

问题


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.

What would I put in here?

Here is my starting code:

// 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 ); 

Any help is appreciated.


回答1:


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;
}

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



来源:https://stackoverflow.com/questions/49555463/filter-woocommerce-products-based-on-custom-product-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!