You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义子、孙产品分类术语短代码工作异常问题

问题分析

你的代码逻辑存在漏洞:

  • child_category_shortcode 只要遇到parent≠0的分类就直接返回,但产品可能同时被标记了子分类和孙分类,循环如果先遍历到孙分类,就会错误返回孙分类名称。
  • grandchild_category_shortcode 的判断逻辑不够严谨,没有准确锁定孙分类的层级特征。
修正后的代码
/**
 * Brandname for Product Single Page shortcode - 显示子分类(父级为顶级分类的分类)
 */
function child_category_shortcode($atts) {
    global $post;
    
    $product_terms = get_the_terms($post->ID, 'product_cat');
    
    if (!empty($product_terms)) {
        foreach ($product_terms as $term) {
            // 获取当前分类的父分类
            $parent_term = get_term($term->parent, 'product_cat');
            // 判断父分类是否为顶级分类(父分类的parent为0)
            if ($parent_term && $parent_term->parent === 0) {
                return $term->name;
            }
        }
    }
    // 兜底返回空或自定义默认值
    return '';
}
add_shortcode('brandname', 'child_category_shortcode');

/**
 * Productname for Product Single Page shortcode - 显示孙分类(父级为子分类的分类)
 */
function grandchild_category_shortcode($atts) {
    global $post;
    
    $product_terms = get_the_terms($post->ID, 'product_cat');
    
    if (!empty($product_terms)) {
        foreach ($product_terms as $term) {
            // 获取当前分类的父分类
            $parent_term = get_term($term->parent, 'product_cat');
            // 判断父分类是否有自己的父分类(即当前分类是孙分类)
            if ($parent_term && $parent_term->parent !== 0) {
                return $term->name;
            }
        }
    }
    // 兜底返回空或自定义默认值
    return '';
}
add_shortcode('productname', 'grandchild_category_shortcode');
逻辑说明
  • brandname短代码:遍历产品关联的所有分类,筛选出「父分类是顶级分类(parent=0)」的分类,也就是层级结构里的子分类(比如示例中的Apple)。
  • productname短代码:遍历产品关联的所有分类,筛选出「父分类本身还有父分类」的分类,也就是层级结构里的孙分类(比如示例中的iPad Pro 12.9 inch (5th gen))。
  • 增加了get_term的有效性判断,避免无效分类导致的报错;同时添加兜底返回值,防止出现空输出问题。

内容的提问来源于stack exchange,提问作者ken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:16:28