问题
I've got the following args defined as a part of my query:
$args = apply_filters('woocommerce_related_products_args', array(
'post_type' => 'product',
'author' => $artist,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
)
) );
$products = new WP_Query( $args );
I need to exclude a category called Magazines (slug "magazines") or ID 351 from the query.
I've been trying to include 'category__not_in' => array('magazines')
, so it looks like this:
$args = apply_filters('woocommerce_related_products_args', array(
'post_type' => 'product',
'author' => $artist,
'post_status' => 'publish',
'category__not_in' => array('magazines'),
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
)
) );
$products = new WP_Query( $args );
But that just doesn't seem to be working.
What am I doing wrong here?
回答1:
Product categories are a custom taxonomy product_cat
.
So you need to do it in a simple tax_query
this way:
$args = apply_filters('woocommerce_related_products_args',
array(
'post_type' => 'product',
'author' => $artist,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
),
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug', // Or 'name' or 'term_id'
'terms' => array('magazines'),
'operator' => 'NOT IN', // Excluded
)
)
)
);
$products = new WP_Query( $args );
回答2:
You should use category__not_in
value as an array like this
$query = new WP_Query( array( 'category__not_in' => array( 'magazines' ) ) );
For details check this
WP_Query
So please update your code into this
$args = apply_filters('woocommerce_related_products_args', array(
'post_type' => 'product',
'author' => $artist,
'post_status' => 'publish',
'category__not_in' => array('magazines')
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
)
) );
$products = new WP_Query( $args );
Let me know whether its working or not for you.
来源:https://stackoverflow.com/questions/47630487/exclude-a-woocommerce-product-category-from-a-wp-query