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

WordPress模板嵌套if else语句else分支无法执行问题求助

问题原因

  • 代码中的else分支仅与if( have_rows('hero') )条件配对,只有当hero字段组完全没有配置数据时才会触发。
  • 只要hero字段组存在有效配置,哪怕内部的背景图片字段为空,代码都会进入if( have_rows('hero') )的成立分支,仅会因为内层if($image)判断不成立而无输出,不会走到else分支,和预期的「背景图不存在就执行else」的逻辑不匹配。

修复方案

新增标记变量判断是否存在有效背景图即可,修改后代码如下:

<?php
if ( is_singular() || is_page() ):
    $has_hero_bg = false;
    if( have_rows('hero') ): while( have_rows('hero') ): the_row();
        if( have_rows('hero_-_background_options') ): while( have_rows('hero_-_background_options') ): the_row();
            $image = get_sub_field('background_-_image');
            if($image):
                $has_hero_bg = true;
?>
.default-hero .col .hero-bkg {
    display:none;
}
<?php  endif; endwhile; endif; endwhile; endif;
// 无有效背景图时输出对应样式
if(!$has_hero_bg):
?>
.default-hero.relative.bg-grey-light {
  display: none;
}
<?php endif; endif; ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:06:07