问题
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