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

插入PHP代码导致下方ACF字段消失的技术咨询

问题原因与解决方法

你的问题出在循环里的setup_postdata( $post )——这个函数会覆盖WordPress的全局$post变量,而你循环结束后没有重置它。当后续调用the_field('fieldname')时,ACF是在循环最后一个帖子的上下文里找字段,不是当前页面/帖子的上下文,找不到内容就不会输出任何东西。

解决办法很简单,在循环结束后加上wp_reset_postdata(),恢复全局$post变量即可:

<?php
$args = array( 'post_type' => 'post', 'numberposts' => -1);
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ): setup_postdata( $post );
?>
<div class="col">
<p class="ingress">&ldquo;<?php the_field('review'); ?>&rdquo;</p>
<img src="<?php the_field('star_rating'); ?>" class="star-rating"><br>
<img src="<?php the_field('image'); ?>" class="avatar">
<p class="name-location"><?php the_field('name_location'); ?></p>
</div>
<?php 
endforeach;
wp_reset_postdata(); // 重置全局$post,回到当前页面的上下文
?>

wp_reset_postdata()会把全局$post变量恢复到循环执行前的状态,这样后续的ACF字段调用就能正确读取当前页面的字段内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:31:41