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

WordPress中ACF关联字段按年份排序:选Post Object还是Relationship?

ACF Relationship字段按年份倒序排序实现及字段选择建议

一、代码实现按年份倒序排序

你当前的代码是直接按ACF后台添加顺序输出关联内容,要实现按date_released字段的年份倒序(新到旧),可以在获取关联数据后用usort函数排序,具体修改如下:

<?php include_once('header.php');?>
<?php the_title();?>
<?php
    $featured_posts = get_field('stars_relationship');
    if( $featured_posts ): 
        // 按date_released字段倒序排序(新年份在前)
        usort($featured_posts, function($postA, $postB) {
            // 获取两个关联帖子的date_released字段值
            $dateA = get_field('date_released', $postA->ID);
            $dateB = get_field('date_released', $postB->ID);
            
            // 转换为时间戳进行比较(兼容大多数日期格式)
            $timestampA = strtotime($dateA);
            $timestampB = strtotime($dateB);
            
            // 倒序排列:返回值为负则postA在前,正则postB在前
            return $timestampB - $timestampA;
        });
?>
    <ul>
    <?php foreach( $featured_posts as $post ): 
        setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <span>发布日期: <?php the_field( 'date_released'); ?></span>
            <?php
            $date = get_field("date_released");
            $dateTime = DateTime::createFromFormat("Ymd", $date); // 这里需匹配你的DatePicker返回格式
            
            if ( is_object($dateTime) ) {
              $month = $dateTime->format('F');
              $year = $dateTime->format('Y');
              // 可在此添加年份/月份的显示逻辑
              echo "<span>年份: {$year}</span>";
            }
            ?>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php 
    wp_reset_postdata(); ?>
<?php endif; ?>

<?php include_once('footer.php');?>

注意事项

  • 确保date_released字段的返回格式是合法的日期格式(如Ymd、Y-m-d等),strtotime能正常解析;如果你的DatePicker返回的是纯年份(如2024),可以直接用数值比较:
    usort($featured_posts, function($postA, $postB) {
        $yearA = (int)get_field('date_released', $postA->ID);
        $yearB = (int)get_field('date_released', $postB->ID);
        return $yearB - $yearA;
    });
    

二、Post Object vs Relationship字段选择建议

  • Relationship字段:适合你的当前场景,它支持选择多个关联帖子,返回值是帖子对象数组,能满足你展示多条关联内容的需求。
  • Post Object字段:仅支持选择单个帖子,返回单个帖子对象,适合只需要关联单篇内容的场景(比如设置一篇「推荐文章」)。

所以你需要展示多个关联内容时,Relationship字段是更合适的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:10:55