WordPress:替代get_pages获取子页面ACF字段的方案
解决WordPress中get_pages无法获取ACF字段的问题及替代方案
问题原因
你当前代码里的the_field('job_title')无法读取子页面ACF字段,是因为ACF的the_field()默认依赖全局$post对象,而get_pages()返回的是独立的WP_Post对象列表,不会自动更新全局$post,所以函数无法定位到对应的子页面字段。
另外你的$args里有个语法错误:'sort_column" => "post_name'的引号不匹配,应该改成'sort_column' => 'post_name'(该错误不影响ACF字段读取,但会导致排序参数失效)。
两种解决方法
方法1:修改现有代码,给ACF函数指定页面ID
不需要替换get_pages,只需在调用ACF字段时明确传入子页面ID即可:
<?php $args = array( 'parent' => $post->ID, 'post_type' => 'page', 'numberposts' => -1, 'post_status' => 'publish', 'sort_order' => 'DESC', 'sort_column' => 'post_name', // 修复引号错误 'orderby' => 'menu_order', 'order' => 'ASC' ); $pages = get_pages($args); ?> <div class="childrenFetchedLoopWrapper"> <?php foreach( $pages as $page ) { ?> <div class="feedItemWrapper wpb_animate_when_almost_visible wpb_fadeInUp fadeInUp" style="background-image: url('<?php echo get_the_post_thumbnail_url($page->ID, 'full'); ?>')"> <a href="<?php echo get_permalink($page->ID); ?>" rel="bookmark" title="<?php echo $page->post_title; ?>"> <img src="/wp-content/themes/salient-child/images/aspectTrans.png" alt="*" title="*" /> <h3><?php echo $page->post_title; ?></h3> <!-- 给the_field传入子页面ID --> <p><?php the_field('job_title', $page->ID); ?></p> </a> </div> <?php } ?> </div>
也可以用get_field()直接获取值后输出,效果一致:
<p><?php echo get_field('job_title', $page->ID); ?></p>
方法2:用WP_Query替代get_pages(推荐)
WP_Query是WordPress官方推荐的自定义循环方式,它会自动在循环中更新全局$post对象,the_field()、the_title()等模板函数可直接使用,无需额外传ID,代码更符合规范:
<?php $args = array( 'post_parent' => $post->ID, // 对应get_pages的parent参数 'post_type' => 'page', 'posts_per_page' => -1, // 对应numberposts => -1 'post_status' => 'publish', 'orderby' => 'menu_order', 'order' => 'ASC' ); $child_pages_query = new WP_Query($args); if ($child_pages_query->have_posts()) : ?> <div class="childrenFetchedLoopWrapper"> <?php while ($child_pages_query->have_posts()) : $child_pages_query->the_post(); ?> <div class="feedItemWrapper wpb_animate_when_almost_visible wpb_fadeInUp fadeInUp" style="background-image: url('<?php echo get_the_post_thumbnail_url(get_the_ID(), 'full'); ?>')"> <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"> <img src="/wp-content/themes/salient-child/images/aspectTrans.png" alt="*" title="*" /> <h3><?php the_title(); ?></h3> <p><?php the_field('job_title'); ?></p> </a> </div> <?php endwhile; ?> </div> <?php // 重置全局post对象,避免影响后续内容 wp_reset_postdata(); endif; ?>
内容的提问来源于stack exchange,提问作者dubbs
相关产品推荐
相关产品推荐

