Reputation: 129
I had the same question as Quadie as answered in the following thread.
The code as provided by LoicTheAztec works great...
add_filter( 'woocommerce_products_widget_query_args', function( $query_args ){
// Set HERE your product category slugs
$categories = array( 'music', 'posters' );
$query_args['tax_query'] = array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
));
return $query_args;
}, 10, 1 );
... but I would like to know if there is an option to extend this code to be able to set the categories per seperate widget. E.g. I want a products widget for category 1 on a page x, while I want a products widget for category 2 somewhere else on page x.
I was thinking about using a shortcode & specifying the category as an array for this shortcode, but not sure on how to implement this.
Any thoughts on this issue?
This is the shortcode I tried to use:
[productsbycat cat1="broodjes"]
& it triggers the following code:
function productsbycat_func( $atts ) {
$categories = shortcode_atts( array(
'cat1' => 'something',
'cat2' => 'something else',
), $atts );
add_filter( 'woocommerce_products_widget_query_args', function ( $query_args ){
$query_args['tax_query'] = array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $categories,
));
return $query_args;
}, 10, 1 );
}
add_shortcode( 'productsbycat', 'productsbycat_func' );
However, it does not generate anything yet.
Upvotes: 0
Views: 673
Reputation: 253784
Is not possible to extend my code "to be able to set the categories per seperate widget".
For your shortcode only I think that you don't need any code customization for that.
I you look to the WooCommerce Official documentation related to WooCommerce Shortcodes, you will see on section "Product category" this short code: [product_category]
, which main argument is category
You can add one product category slugs this way:
[product_category category="clothing"] // One product category
Or for many product categories slugs (coma separated) this way:
[product_category category="posters,music"]
The default arguments settings (that you can change) are:
$args = array(
'per_page' => "12",
'columns' => "4",
'orderby' => 'title', // or by "menu_order"
'order' => "asc", // or "desc"
'category' => "" // Always only product category slugs
'operator' => "IN" // Possible values are "IN", "NOT IN", "AND".
);
But it will not work as you would like in your product widgets as it will display the product grid loop for the defined categories
You should need to build your own widgets.
Upvotes: 1