特定类别的 Woocommerce 产品小部件
问题描述:
如何让 Woocommerce 产品小部件仅显示特定类别的产品?当前选项包括特价、精选等.
How can I make the Woocommerce Products Widget display Products of a specific Category only? Current options are on-sale, featured, and all.
答
这可以通过挂在 woocommerce_products_widget_query_args
过滤器钩子中的自定义函数来完成.您必须在其中的数组中设置您的产品类别(或者您的产品类别,如果有多个).
This can be done with a custom function hooked in woocommerce_products_widget_query_args
filter hook. You will have to set inside it, in the array, your product category (or your product categories if more than one).
代码如下:
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 );
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
在 WooCommerce 3+ 中测试并有效
Tested in WooCommerce 3+ and works