如何用PHP隐藏ACF未填写内容的按钮及其他字段
修改后的ACF Repeater代码
<?php if( have_rows('feature_slider') ): ?> <div class="swiper-container"> <div class="swiper-wrapper"> <?php while( have_rows('feature_slider') ): the_row(); $feature_image = get_sub_field('feature_image'); $card_heading = get_sub_field('card_heading'); $card_description = get_sub_field('card_description'); $card_button_text = get_sub_field('card_button_text'); $card_link_url = get_sub_field('card_link_url'); ?> <!-- slider --> <div class="swiper-slide"> <div class="bg--pattern"></div> <div class="absolute c-card"><div class="card-content"> <h2><?php echo esc_html($card_heading); ?></h2> <p><?php echo esc_html($card_description); ?></p> <?php if( !empty($card_button_text) && !empty($card_link_url) ): ?> <a class="card-btn" href="<?php echo esc_url($card_link_url); ?>"><?php echo esc_html($card_button_text); ?> ⟶</a> <?php endif; ?> </div></div> <img src="<?php echo esc_url($feature_image['url']); ?>" alt="<?php echo esc_attr($feature_image['alt']); ?>" /> <div class="c--content-card"> <h2><?php echo esc_html($card_heading); ?></h2> <p><?php echo esc_html($card_description); ?></p> </div> <!-- card --> </div> <!-- swiper slide --> <?php endwhile; ?> <?php endif; ?>
通用ACF字段隐藏方法
- 先存值再判断:别直接用
the_sub_field()/the_field()输出字段,先用get_sub_field()/get_field()把字段值存入变量,方便后续判断操作。 - 条件判断逻辑:
- 单个字段:如果字段为空就不输出对应HTML,用
if( !empty($字段变量) )判断(empty()会自动处理空字符串、null、false等无效情况)。 - 关联字段(比如按钮的文本+链接):需要多个字段都不为空才输出,用
&&连接多个!empty()判断,确保所有必要内容都存在再渲染。
- 单个字段:如果字段为空就不输出对应HTML,用
- 安全输出字段:输出文本用
esc_html(),输出链接用esc_url(),输出图片alt用esc_attr(),避免XSS漏洞和非法字符导致的页面异常。
内容的提问来源于stack exchange,提问作者Churchill
相关产品推荐
相关产品推荐

