如何在WooCommerce子分类中获取完整的产品分类层级路径?
解决WooCommerce产品分类完整层级路径显示问题
问题分析
你的现有代码仅获取了产品的单个分类名称(循环到第一个分类就终止),没有遍历当前分类的所有父级分类,因此无法输出完整的层级路径。
解决方案代码
$terms = get_the_terms($product->ID, 'product_cat'); if ($terms && !is_wp_error($terms)) { // 获取第一个关联分类(若产品有多个分类,可按需调整筛选逻辑) $current_term = reset($terms); $term_path = []; // 获取当前分类的所有父级分类ID,返回顺序为「直接父级 → 顶级分类」 $ancestors = get_ancestors($current_term->term_id, 'product_cat', 'taxonomy'); // 遍历父级ID,获取对应分类名称并加入路径数组 foreach ($ancestors as $ancestor_id) { $ancestor_term = get_term($ancestor_id, 'product_cat'); if ($ancestor_term && !is_wp_error($ancestor_term)) { $term_path[] = $ancestor_term->name; } } // 反转父级数组,调整为「顶级分类 → 直接父级」顺序,再加入当前分类名称 $term_path = array_reverse($term_path); $term_path[] = $current_term->name; // 拼接成空格分隔的完整路径字符串 $full_category_path = implode(' ', $term_path); echo $full_category_path; }
代码说明
get_ancestors():专门用于获取分类/帖子的父级ID链,这里指定分类法为product_cat,确保只获取WooCommerce产品分类的父级。reset($terms):快速获取数组第一个分类对象,若产品关联多个分类,可通过判断$term->parent或分类层级,筛选出你需要的目标分类。array_reverse():修正父级分类的顺序,让路径从顶级到当前子分类依次排列。
多分类场景优化
如果产品关联多个分类,可自动选择层级最深的分类生成路径:
$terms = get_the_terms($product->ID, 'product_cat'); if ($terms && !is_wp_error($terms)) { $deepest_term = null; // 遍历找出层级最深的分类 foreach ($terms as $term) { $current_depth = count(get_ancestors($term->term_id, 'product_cat')); $deepest_depth = $deepest_term ? count(get_ancestors($deepest_term->term_id, 'product_cat')) : -1; if ($current_depth > $deepest_depth) { $deepest_term = $term; } } if ($deepest_term) { $term_path = []; $ancestors = get_ancestors($deepest_term->term_id, 'product_cat', 'taxonomy'); foreach ($ancestors as $ancestor_id) { $ancestor_term = get_term($ancestor_id, 'product_cat'); if ($ancestor_term && !is_wp_error($ancestor_term)) { $term_path[] = $ancestor_term->name; } } $term_path = array_reverse($term_path); $term_path[] = $deepest_term->name; $full_category_path = implode(' ', $term_path); echo $full_category_path; } }
内容的提问来源于stack exchange,提问作者Karim Sin
相关产品推荐
相关产品推荐

