WordPress预览中模板部件的ACF字段内容不显示求助
问题原因与解决方案
核心问题
Gutenberg预览模式的上下文与前端渲染存在差异,直接调用get_field()时,ACF可能无法正确关联当前正在编辑的页面ID,导致字段值无法读取;另外也可能是字段组的显示规则未覆盖预览场景。
解决步骤
1. 显式指定Post ID获取字段值
在模板部件代码中,明确传递当前页面的ID给get_field()函数,确保ACF精准读取对应页面的字段:
<div id="hero" class="h-3/5-screen md:h-screen"> <?php // 获取当前页面ID,预览模式下确保上下文正确 $current_post_id = get_the_ID(); $hero_background_image = get_field('hero_background-image', $current_post_id); $hero_heading_h1 = get_field('hero_heading-h1', $current_post_id); ?> <?php if ($hero_background_image) : ?> <div class="blue-to-green-gradient w-full h-full relative"> <img class="object-cover object-center w-full h-full absolute top-0 left-0 -z-20 grayscale" src="<?php echo esc_url($hero_background_image['url']); ?>" alt="<?php echo esc_attr($hero_background_image['alt']); ?>" /> <div class="w-full h-full px-6 pb-16 md:px-12 md:pb-24 lg:pb-40 xl:px-36 max-w-screen-2xl mx-auto"> <?php if ($hero_heading_h1) : ?> <h1 class="text-white text-4xl md:text-7xl xl:text-8xl font-semibold flex items-end h-full hyphens-auto md:hyphens-none"><?php echo esc_html($hero_heading_h1); ?></h1> <?php endif; ?> </div> </div> <?php endif; ?> <div id="scroll-down" class="hidden md:block absolute md:right-12 lg:left-1/2 lg:-translate-x-1/2 bottom-8 h-10 w-10 z-50"><img src="<?php echo get_stylesheet_directory_uri() . '/assets/arrow-scroll.svg'; ?>" alt="contact" class="object-contain object-center w-10 h-auto" /></div> </div>
2. 验证ACF字段组的显示规则
进入ACF字段组编辑页面,确认字段组的显示规则已覆盖当前使用的「Front Page」模板,或者直接指定为「首页」/「页面」类型,确保预览时字段组能被正确加载。
3. 临时禁用缓存排查
如果站点启用了缓存插件(如WP Rocket、W3 Total Cache),临时禁用缓存后重新预览,避免旧的缓存内容干扰字段值的读取。
4. 确保ACF在预览环境加载
若上述步骤无效,可在主题的functions.php中添加代码,强制ACF脚本在预览模式下加载:
add_action('wp_enqueue_scripts', function() { if (is_preview()) { acf_enqueue_scripts(); } });
内容的提问来源于stack exchange,提问作者Ramate
相关产品推荐
相关产品推荐

