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

WordPress自定义分类法模板仅存在子分类时展示HTML的问题

代码问题及修复代码

存在的问题

  • 条件判断变量错误:is_wp_error()判断的$terms为未定义变量,逻辑完全失效,实际查询子分类的存储变量为$term_children
  • 逻辑运算符错误:使用||(或逻辑),只要任意条件成立就输出HTML,即便子分类数量为0也会触发渲染
  • 数量判断方式错误:get_terms()返回分类数组,无法通过->count读取数量,需使用count()函数统计数组长度
  • 循环内变量错误:读取分类图片时使用未定义的$term变量,需替换为循环内的子分类对象$child,否则无法正确拉取每个子分类的自定义图片

修复后完整代码

<?php
$term_children = get_terms('onderwerp', array( 
    'parent' => get_queried_object_id(),
    'hide_empty' => false // 需隐藏无文章的子分类可将值改为true
));
// 仅当查询无错误且存在子分类时输出HTML内容
if ( ! is_wp_error( $term_children ) && count( $term_children ) > 0 ) { ?>
    <section>
    <h2>Ik heb een vraag over:</h2>
    <div class="onderwerp-links">
    <?php
    foreach ( $term_children as $child ) { 
        $img = get_term_meta( $child->term_id, 'ndftm_img', true ); 
    ?>
            <a href="<?php echo esc_url( get_term_link( $child ) ) ?>" style="background-image: url(<?php echo esc_url($img); ?>)">
            <span><?php echo esc_html( $child->name ); ?></span>
            </a>
    <?php } ?>
    </div>
    </section>
<?php } ?>

额外说明

修复代码中新增了字段值转义输出逻辑,符合WordPress代码安全规范,可避免XSS安全漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:51:04