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

WordPress新手求助:自定义选择文章展示至Hero Grid

解决WordPress Hero Grid自定义选择文章的问题

嘿,我来帮你搞定这个自定义选文章的需求!你之前尝试用ACF的方向完全没错,只是没把ACF的字段值和WP_Query结合起来而已。下面是一步步的实操方案:

第一步:用ACF创建文章选择字段

先在ACF里搭好能让你手动选文章的字段:

  • 打开ACF的字段组设置,新建一个字段组(比如叫「Hero Grid 精选设置」)
  • 字段类型选 Relationship(要选多篇的话这个最合适,单篇可以用Post Object)
  • 字段配置里:
    • 允许的文章类型勾选 Post
    • 把「选择数量」设为3(和你当前要展示的数量对应)
    • 把这个字段组关联到你要显示Hero Grid的页面(比如首页、特定页面模板)
    • 记住字段名,比如我这里用 featured_hero_posts

第二步:修改WP_Query代码实现自定义选择

把你原来的WP_Query部分替换成下面的代码,这样就能调用你通过ACF选中的文章了:

<section class="page-wrap">
 <div class="container-sm">
 <h1><?php the_title();?></h1>
 <?php get_template_part('includes/section','content');?>
 </div>

 <?php 
 // 获取ACF选中的文章ID数组
 $selected_post_ids = get_field('featured_hero_posts');

 // 配置WP_Query参数
 $args = array(
  'post_type' => 'post',
  'posts_per_page' => 3,
  // 有选中文章就用选中的,没选就显示最新3篇
  'post__in' => $selected_post_ids ? $selected_post_ids : array(),
  'orderby' => 'post__in', // 保持你在ACF里选择的顺序
  'post_status' => 'publish'
 ); 

 $_posts = new WP_Query($args); 
 ?>

 <?php if($_posts->have_posts()):?>
 <div class="row mt-5">
 <?php while($_posts->have_posts()) : $_posts->the_post();?>
 <?php 
 // 简化缩略图获取逻辑
 $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'caursel');
 // 可选:没有缩略图时设置默认图
 if(!$thumbnail_url) {
  $thumbnail_url = '你的默认图片URL';
 }
 ?>
 <div id="post-<?php the_ID(); ?>" class="hero-grid-item" style="background-image:url('<?php echo esc_url($thumbnail_url); ?>');">
 <a href="<?php the_permalink();?>">
 <h3><?php the_title();?></h3>
 </a>
 <h6><?php the_excerpt();?></h6>
 </div>
 <?php endwhile;?>
 <?php wp_reset_postdata(); // 重置查询,避免影响后续循环 ?>
 </div>
 <?php else: ?>
 <!-- 无文章时的提示 -->
 <p>暂无精选文章</p>
 <?php endif;?>
 </section>

第三步:优化小建议(可选但推荐)

  • 把内联样式移到CSS文件里,维护更方便:
    .hero-grid-item {
      width: 440px;
      margin-left: 3px;
      padding: 10px;
      border-radius: 10px;
      display: flex;
      align-items: center; /* 你原来的align:center应该是这个哦 */
      background-size: cover;
      background-position: center;
    }
    
  • 用esc_url()包裹图片URL,避免安全问题
  • 加上wp_reset_postdata(),防止后续WordPress循环出现异常

现在你去对应页面的编辑界面,就能通过ACF字段手动选择要展示在Hero Grid里的文章了,而且选择的顺序会和前端显示的顺序完全一致!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:38:15