ACF字段在Insights归档页面循环中无法显示的问题求助
解决ACF字段在自定义文章类型归档页面无法获取的问题
问题根源分析
- 变量赋值顺序错误:你在归档循环里先尝试从
$content取play_time,但$content是之后才用get_field获取的,此时$content未定义或为空,自然拿不到值。 - ACF字段组的规则限制:你的字段组仅绑定给「使用Video模板的Insights文章」,归档循环可能包含未使用该模板的文章,这类文章没有对应字段,即使修正顺序也会显示空值。
- 自定义循环的上下文问题:在自定义
WP_Query循环中,全局上下文可能不稳定,需明确指定文章ID来确保get_field获取正确数据。
具体解决步骤
步骤1:修正变量赋值顺序
先获取content字段,再从中提取play_time,同时用空值合并运算符避免字段不存在时报错:
// 先获取当前文章的content字段 $content = get_field('content'); // 再提取play_time,字段不存在时返回空字符串 $playtime = $content['play_time'] ?? '';
步骤2:添加模板判断,仅对Video模板文章显示时长
因为字段组只绑定给Video模板的文章,需先判断当前文章模板,再渲染时长:
// 获取当前文章的模板slug(insights_video.php一般会返回insights-video.php) $current_template = get_page_template_slug(get_the_ID()); if ($current_template === 'insights-video.php') { $content = get_field('content', get_the_ID()); $playtime = $content['play_time'] ?? ''; // 仅当play_time有值时显示 if (!empty($playtime)) { echo '<p class="dashicons-before dashicons-clock"> ' . esc_html($playtime) . ' mins</p>'; } }
步骤3:自定义循环中明确传入文章ID
在自定义WP_Query循环里,调用get_field时传入当前文章ID,确保获取对应文章的字段:
// 传入文章ID获取content字段 $content = get_field('content', get_the_ID());
完整修正后的归档循环代码
整合所有修正,并添加WordPress安全转义(esc_html/esc_url)的最佳实践:
<?php if ($insights->have_posts()) : while ($insights->have_posts()) : $insights->the_post(); $topics = get_the_terms(get_the_ID(), 'topic'); $images = get_field('images', get_the_ID()); $current_template = get_page_template_slug(get_the_ID()); $playtime = ''; $content_summary = ''; // 仅处理使用Video模板的文章 if ($current_template === 'insights-video.php') { $content = get_field('content', get_the_ID()); $playtime = $content['play_time'] ?? ''; $content_summary = $content['summary'] ?? ''; } else { // 非Video模板文章直接获取summary $content_summary = get_field('content', get_the_ID())['summary'] ?? ''; } ?> <div class="tst-content-tile"> <a href="<?= esc_url(get_permalink()) ?>" class="tst-content-tile__image"> <div class="tst-content-tile__image-inside" style="background-image: url(<?= esc_url($images['preview_image']['sizes']['large'] ?? '') ?>)"></div> <div class="tst-content-tile__image-overlay"> <div class="tst-content-tile__image-overlay-blue"></div> <img src="<?= esc_url(get_stylesheet_directory_uri()) ?>/assets/images/content-tile-link-arrow.svg" class="tst-content-tile__image-overlay-arrow"> </div> </a> <div class="tst-content-tile__tags-container"> <?php if($topics): ?> <?php foreach($topics as $topic): ?> <div class="tst-content-tile__tag"><?= esc_html($topic->name) ?></div> <?php endforeach; ?> <?php endif; ?> </div> <h5><?= esc_html(get_the_title()) ?></h5> <?php if (!empty($playtime)) : ?> <p class="dashicons-before dashicons-clock"> <?= esc_html($playtime) ?> mins</p> <?php endif; ?> <p><?= esc_html($content_summary) ?></p> <a href="<?= esc_url(get_permalink()) ?>" class="tst-button">Read more</a> </div> <?php endwhile; ?> <?php endif; wp_reset_query(); ?>
内容的提问来源于stack exchange,提问作者Jonny Quinn
相关产品推荐
相关产品推荐

