WordPress中ACF的get_field()返回null与变量声明顺序相关问题
问题原因
你的全局$post对象被异常修改了,这是导致ACF字段读取和the_title()输出异常的核心原因:
- 你给两个select字段开了AJAX动态加载,且默认
choices为空,说明你一定是通过acf/load_field之类的钩子动态填充选项,这段填充代码里的自定义查询没有执行wp_reset_postdata(),或者直接修改了全局$post变量且没有还原。 - 第一次调用
get_field()时会触发选项填充逻辑,全局$post被修改后没有恢复,后续调用get_field()或者the_title()读取的都是被污染的全局变量,自然返回错误结果。
解决方案
临时修复(快速验证问题)
在循环内调用get_field()时强制传入当前文章ID,绕开被污染的全局$post:
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php $current_pid = get_the_ID(); // 先拿到当前文章的固定ID ?> <a href="#contact_form?<?php echo get_the_title($current_pid) ?>" class="card--link"> <div class="card"> <div class="card--header"> <h3><?php the_title() ?></h3> </div> <div class="card--body"> <p><?php the_field("content", $current_pid) ?></p> <?php $stagesId = get_field("stages", $current_pid); $jobsId = get_field("job", $current_pid); var_dump($jobsId); var_dump($stagesId); ?> <p>Nombre de personne disponible pour ces jobs : <?php echo $count ?></p> </div> </div> </a> <?php endwhile; ?>
修改后如果两个字段都能正常返回值、the_title()输出也正常,即可确认是全局$post污染问题。
永久修复
找到你用来动态填充job和stages两个select字段选项的代码,检查其中的自定义查询逻辑:
- 所有自定义
WP_Query循环结束后必须执行wp_reset_postdata()还原全局post对象 - 不要直接给
global $post赋值,如有特殊赋值操作,执行完后要把原本的$post对象还原回去
补充排查项
如果上述操作后仍有问题,可以尝试修改两个ACF字段的别名,避免和WordPress内置查询参数重名:比如把job改为job_select、stages改为stage_select,同时同步修改代码里的字段名即可。
内容的提问来源于stack exchange,提问作者Beatles BOB
相关产品推荐
相关产品推荐

