如何在WooCommerce各级产品子分类页面显示指定内容
解决WooCommerce深层产品分类页面显示指定内容的问题
原代码仅能匹配父分类和一级子分类,无法覆盖更深层级的子分类——原因是它只判断了当前分类的直接父ID是否为目标值,而深层子分类的直接父并非指定的233/232,因此无法触发对应逻辑。
解决方案一:使用term_is_ancestor_of()函数(推荐)
这个函数可以递归验证当前分类是否属于某个父分类的后代(包含所有层级),代码修改如下:
add_action( 'woocommerce_archive_description', 'add_slide_text', 1 ); function add_slide_text() { if ( ! is_product_category() ) { return; // 非产品分类页面直接终止逻辑 } $current_cat = get_queried_object(); // 定义父分类ID,方便后续修改维护 $man_cat_id = 233; $woman_cat_id = 232; // 匹配Man分类本身,或所有属于Man的子分类(含深层) if ( is_product_category('man') || term_is_ancestor_of( $man_cat_id, $current_cat, 'product_cat' ) ) { echo 'Hello man'; } // 匹配Woman分类本身,或所有属于Woman的子分类(含深层) elseif ( is_product_category('woman') || term_is_ancestor_of( $woman_cat_id, $current_cat, 'product_cat' ) ) { echo 'Hello woman'; } }
代码说明:
term_is_ancestor_of( $父分类ID, $当前分类对象, $分类法 ):自动检查当前分类的所有上层分类,只要属于目标父分类的后代,就返回true。- 提前判断非产品分类页面直接返回,减少不必要的运算。
- 将分类ID定义为变量,后续修改时只需改动变量值即可。
解决方案二:使用get_ancestors()函数
通过获取当前分类的所有祖先ID数组,再检查目标父ID是否在数组中,同样能覆盖所有层级的子分类:
add_action( 'woocommerce_archive_description', 'add_slide_text', 1 ); function add_slide_text() { if ( ! is_product_category() ) { return; } $current_cat = get_queried_object(); $man_cat_id = 233; $woman_cat_id = 232; // 获取当前分类的所有上层分类ID数组(从直接父级到顶级分类) $ancestors = get_ancestors( $current_cat->term_id, 'product_cat' ); // 匹配Man分类本身,或祖先包含Man分类ID的子分类 if ( is_product_category('man') || in_array( $man_cat_id, $ancestors ) ) { echo 'Hello man'; } // 匹配Woman分类本身,或祖先包含Woman分类ID的子分类 elseif ( is_product_category('woman') || in_array( $woman_cat_id, $ancestors ) ) { echo 'Hello woman'; } }
代码说明:
get_ancestors()返回当前分类所有上层分类的ID数组,in_array()用于检查目标父ID是否存在于数组中。- 逻辑清晰,适合需要对祖先分类做更多自定义处理的场景。
内容的提问来源于stack exchange,提问作者Lgane
相关产品推荐
相关产品推荐

