为带子类的默认WooCommerce商品分类列表小部件添加“Show all products”
给WooCommerce默认商品分类小部件添加“显示全部商品”选项
要给带有子分类的父分类添加“显示全部商品”列表项,直接通过过滤WooCommerce分类列表的输出即可实现,无需修改核心文件。将以下代码添加到你的主题functions.php文件或者自定义功能插件中:
add_filter( 'woocommerce_list_categories', 'add_show_all_products_to_parent_categories', 10, 2 ); function add_show_all_products_to_parent_categories( $output, $args ) { // 仅对商品分类小部件生效 if ( ! isset( $args['widget'] ) || ! $args['widget'] ) { return $output; } // 匹配包含子分类的父分类的子列表起始部分 $pattern = '/(<li class="cat-item cat-item-\d+ has-children"><a[^>]+>[^<]+<\/a>\s*<ul class="children">)/'; // 回调函数插入“显示全部商品”项 $output = preg_replace_callback( $pattern, function( $matches ) { // 提取父分类的URL preg_match('/<a href="([^"]+)"/', $matches[1], $href_matches); if ( isset( $href_matches[1] ) ) { $parent_url = esc_url( $href_matches[1] ); $show_all_item = '<li><a href="' . $parent_url . '">显示全部商品</a></li>'; return $matches[1] . $show_all_item; } return $matches[1]; }, $output ); return $output; }
代码说明
- 这个函数通过
woocommerce_list_categories过滤器拦截分类小部件的HTML输出,精准定位带有子分类的父分类。 - 提取父分类的归档页URL,在其子分类列表的最开头插入“显示全部商品”链接——父分类归档页默认会展示该分类下的所有商品(包含所有子分类商品),正好满足需求。
- 如果你的主题或其他插件修改了分类小部件的HTML结构,可能需要微调正则表达式的匹配规则,默认适配WooCommerce原生结构。
内容的提问来源于stack exchange,提问作者akoggy
相关产品推荐
相关产品推荐

