WooCommerce动态显示兄弟分类和直接子分类列表
在WooCommerce电商网站开发中,分类导航的灵活性直接影响用户的购物体验。很多场景下我们需要在分类页面同时展示当前分类的直接子分类,以及同层级的兄弟分类,方便用户快速切换同级别分类或者进入下一级子类目。本文将介绍如何通过自定义函数实现这个需求,不需要依赖额外的插件,直接通过代码即可完成功能。
实现思路说明
要实现动态显示兄弟分类和直接子分类,核心逻辑分为三步:
- 首先获取当前访问的WooCommerce产品分类对象,确认当前所属的分类层级
- 如果当前分类存在父分类,就获取父分类下的所有子分类作为兄弟分类;如果当前是顶级分类,则兄弟分类为空
- 获取当前分类下的所有直接子分类,最后将两类分类合并后输出列表
核心代码实现
把下面的代码添加到当前主题的functions.php文件中,就可以注册一个可用的短代码,之后在任意页面、文章或者小工具中通过短代码调用即可。
/**
* 显示WooCommerce当前分类的兄弟分类和直接子分类
* 使用方法:在文章/页面中插入短代码 [wc_sibling_child_cats]
*/
function display_wc_sibling_child_cats() {
// 仅在产品分类页面生效
if (!is_product_category()) {
return '';
}
// 获取当前分类对象
$current_term = get_queried_object();
if (!$current_term || !isset($current_term->term_id)) {
return '';
}
$current_term_id = $current_term->term_id;
$parent_term_id = $current_term->parent;
$output = '';
// 获取兄弟分类:如果有父分类,就取父分类下的所有子分类,排除当前分类本身
$sibling_cats = [];
if ($parent_term_id > 0) {
$sibling_args = [
'taxonomy' => 'product_cat',
'parent' => $parent_term_id,
'hide_empty' => false, // 可以根据需求改为true,只显示有产品的分类
'exclude' => [$current_term_id] // 排除当前分类
];
$sibling_cats = get_terms($sibling_args);
}
// 获取当前分类的直接子分类
$child_args = [
'taxonomy' => 'product_cat',
'parent' => $current_term_id,
'hide_empty' => false
];
$child_cats = get_terms($child_args);
// 合并两类分类,先放兄弟分类,再放子分类
$all_cats = array_merge($sibling_cats, $child_cats);
// 如果有分类才输出列表
if (!empty($all_cats) && !is_wp_error($all_cats)) {
$output .= '<div class="wc-cat-nav-list">';
$output .= '<h3>相关分类</h3>';
$output .= '<ul>';
foreach ($all_cats as $cat) {
// 高亮当前分类
$active_class = ($cat->term_id == $current_term_id) ? ' class="current-cat"' : '';
$cat_link = get_term_link($cat);
if (!is_wp_error($cat_link)) {
$output .= '<li' . $active_class . '>';
$output .= '<a href="' . esc_url($cat_link) . '">' . esc_html($cat->name) . '</a>';
$output .= '</li>';
}
}
$output .= '</ul>';
$output .= '</div>';
}
return $output;
}
add_shortcode('wc_sibling_child_cats', 'display_wc_sibling_child_cats');代码功能说明
上述代码首先通过is_product_category()判断当前是否处于WooCommerce产品分类页面,避免在不相关的页面输出内容。接着获取当前分类的信息,通过当前分类的parent属性判断是否有父分类:如果有父分类,就查询父分类下的所有子分类作为兄弟分类,同时排除当前分类本身;如果没有父分类(即当前是顶级分类),则兄弟分类为空。
之后查询当前分类的直接子分类,将两类分类合并后生成无序列表。列表中会给当前分类添加current-cat类,方便后续通过CSS高亮显示当前所在分类。所有输出的链接和文本都使用了WordPress的转义函数,避免安全风险。
使用方法
代码添加之后,你可以在产品分类页面的编辑器中插入短代码[wc_sibling_child_cats],或者在主题模板文件中直接调用echo do_shortcode('[wc_sibling_child_cats]');来输出分类列表。如果需要调整样式,可以给生成的wc-cat-nav-list类添加自定义CSS,比如调整列表间距、高亮颜色等。
注意事项
- 修改主题文件前建议先创建子主题,避免主题更新后代码丢失
- 如果不需要显示空分类,可以把
hide_empty参数改为true - 如果需要调整兄弟分类和子分类的显示顺序,可以在合并数组后自行调整排序逻辑