如何在ACF关联字段中仅显示最新2篇文章
只显示ACF自定义字段中最新2篇文章的实现方法
假设你的ACF字段是「关系(Relationship)」或「文章(Post Object)」类型且开启了多选,以下是两种常见场景的实现代码:
场景1:ACF字段返回文章对象数组
如果你的字段设置为返回文章对象,可以直接对数组排序后截取前2篇:
// 获取ACF字段中的文章列表(替换成你的实际字段名,比如selected_posts) $selected_posts = get_field('selected_posts'); if ($selected_posts) { // 按发布时间降序排序,最新的文章排在最前面 usort($selected_posts, function($a, $b) { return strtotime($b->post_date) - strtotime($a->post_date); }); // 只保留前2篇文章 $latest_posts = array_slice($selected_posts, 0, 2); // 循环输出文章内容 foreach ($latest_posts as $post) { setup_postdata($post); // 初始化文章数据,确保模板函数正常工作 ?> <div class="latest-post"> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <p><?php the_excerpt(); ?></p> <time><?php the_date('Y-m-d'); ?></time> </div> <?php } wp_reset_postdata(); // 重置全局文章数据,避免冲突 }
场景2:ACF字段返回文章ID数组
如果你的字段设置为返回文章ID,可以通过get_posts直接筛选并排序:
// 获取ACF字段中的文章ID列表(替换成你的实际字段名) $post_ids = get_field('selected_posts'); if ($post_ids) { // 查询最新的2篇文章,按发布时间降序排列 $latest_posts = get_posts([ 'post__in' => $post_ids, 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 2, 'post_type' => 'post' // 替换成你的文章类型,比如page或自定义类型 ]); // 循环输出 foreach ($latest_posts as $post) { setup_postdata($post); ?> <div class="latest-post"> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <p><?php the_excerpt(); ?></p> <time><?php the_date('Y-m-d'); ?></time> </div> <?php } wp_reset_postdata(); }
注意事项
- 务必将代码中的
selected_posts替换为你实际创建的ACF字段名称 - 若使用自定义文章类型,需修改
get_posts参数中的post_type值 setup_postdata和wp_reset_postdata是必要步骤,避免全局变量污染导致模板函数异常
内容的提问来源于stack exchange,提问作者Happy Smile
相关产品推荐
相关产品推荐

