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

如何按日期对包含WordPress文章对象的多维关联数组进行排序

如何按日期对包含WordPress(WP)文章对象的多维关联数组进行排序?

要搞定这个需求,我们可以借助PHP的usort()函数,配合自定义的排序回调逻辑来实现,下面是完整的可运行代码示例:

<?php
usort($query, function($post_a, $post_b) { 
    // 比较两篇文章的发布日期,实现降序排列(最新文章在前)
    return $post_b->post_date <=> $post_a->post_date; 
}); 

foreach($query as $post) { 
    // 获取文章缩略图地址
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); 
?> 
<div class="bbr-blog-outer-home"> 
    <div class="lmd-post-img"> 
        <a href="<?php echo get_the_permalink($post->ID); ?>"><img src="<?php echo $image[0]; ?>" alt="" class="img-responsive"></a> 
    </div> 
    <div class="lmd-category"> 
        <a href="<?php the_permalink($post->ID); ?>"><?php echo $category->name; ?></a> 
    </div> 
    <div class="bbr-blog-inner"> 
        <p class="lmd-blog-date"><?php echo get_the_date('',$post); ?></p> 
        <h3><a href="<?php the_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a></h3> 
        <p class="lmd-blog-author"> 
            <?php 
            $lmd_author_id = $post->post_author; 
            the_author_meta( 'display_name' , $lmd_author_id ); 
            ?> 
        </p> 
    </div> 
</div> 
<?php 
}
?>

代码细节说明:

  • 排序逻辑:usort()会遍历数组并应用我们的回调函数,这里用PHP7+的**太空船运算符(<=>)**来比较两个文章对象的post_date属性。$post_b->post_date <=> $post_a->post_date表示把日期更新的文章排在前面(降序),如果需要升序(旧文章在前),只需要把两个变量调换位置即可。
  • 遍历渲染:排序完成后,通过foreach循环逐个处理文章对象:
    • 用wp_get_attachment_image_src()获取指定尺寸的文章缩略图地址
    • 用get_the_permalink()生成文章的永久链接
    • 用get_the_date()获取格式化后的发布日期(括号里的空字符串表示用WordPress默认格式,也可以传入自定义格式比如'Y-m-d')
    • 用the_author_meta()根据文章作者ID获取作者的显示名称
    • 最后把这些数据渲染成前端可展示的HTML结构

注意:代码中的$category变量需要确保已经正确获取(比如在循环外通过get_the_category($post->ID)获取文章分类),否则分类名称会无法正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:02:35