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

WordPress层级分类术语按钮展示代码报错求助

解决WordPress层级分类术语按钮展示的报错问题

问题根源很明确:dci_tipi_evento_array()返回的是多层级嵌套数组,原循环没有区分术语名称字符串和子层级数组,直接把所有元素传给get_term_by()。当传入的是子数组时,get_term_by()无法匹配到有效术语,返回false,后续访问$term->term_id和$term->name自然会触发属性读取警告。

修正方案:递归遍历层级分类数组

因为分类是多层级结构,必须用递归逻辑遍历每一层的术语,区分字符串和子数组:

示例代码(适配键值对式层级数组)

假设你的dci_tipi_evento_array()返回的是类似['父术语' => ['子术语1', '子术语2'], '父术语2']的结构:

// 递归渲染分类按钮
function render_taxonomy_term_buttons($taxonomy_array, $taxonomy_slug) {
    foreach ($taxonomy_array as $key => $value) {
        // 处理父术语(键为术语名称,值为子数组)
        if (is_array($value)) {
            $parent_term = get_term_by('name', $key, $taxonomy_slug);
            if ($parent_term && !is_wp_error($parent_term)) {
                echo '<button data-term-id="' . esc_attr($parent_term->term_id) . '">' . esc_html($parent_term->name) . '</button>';
            }
            // 递归处理子分类
            render_taxonomy_term_buttons($value, $taxonomy_slug);
        } else {
            // 处理独立术语(值为术语名称)
            $term = get_term_by('name', $value, $taxonomy_slug);
            if ($term && !is_wp_error($term)) {
                echo '<button data-term-id="' . esc_attr($term->term_id) . '">' . esc_html($term->name) . '</button>';
            }
        }
    }
}

// 调用函数:传入层级数组和你的分类法别名
$event_types = dci_tipi_evento_array();
render_taxonomy_term_buttons($event_types, '你的分类法slug'); // 替换为实际分类法slug

如果数组是关联数组结构(如[['name' => '父术语', 'children' => [['name' => '子术语']]]])

调整代码适配关联数组:

function render_taxonomy_term_buttons($taxonomy_array, $taxonomy_slug) {
    foreach ($taxonomy_array as $item) {
        // 渲染当前术语
        $term_name = $item['name'] ?? '';
        if (!empty($term_name)) {
            $term = get_term_by('name', $term_name, $taxonomy_slug);
            if ($term && !is_wp_error($term)) {
                echo '<button data-term-id="' . esc_attr($term->term_id) . '">' . esc_html($term->name) . '</button>';
            }
        }
        // 递归处理子分类
        if (!empty($item['children']) && is_array($item['children'])) {
            render_taxonomy_term_buttons($item['children'], $taxonomy_slug);
        }
    }
}

关键注意事项

  1. 匹配数组结构:必须根据dci_tipi_evento_array()返回的实际数组结构,调整代码中术语名称的提取逻辑(比如键名、数组层级)。
  2. 有效性检查:每次调用get_term_by()后,务必检查返回值不是false或WP_Error,避免无效数据触发警告。
  3. 安全输出:用esc_attr()和esc_html()处理按钮的属性和文本,防止XSS攻击。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:55:00