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
相关产品推荐
相关产品推荐

