插入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">“<?php the_field('review'); ?>”</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
相关产品推荐
相关产品推荐

