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

如何展示各分类最新文章并在分类有新文章时动态调整分类排序

修改思路

你的原有代码仅实现了按分类ID排序输出各分类的最新文章,缺少「按分类下最新文章的发布时间对分类排序」的逻辑,以下是可直接使用的修改后代码:

<?php 
// 获取所有分类
$cat_args = array(
    'hide_empty' => true // 可选:隐藏没有文章的空分类,不需要可删除该行
);
$categories = get_categories($cat_args);

// 遍历分类,为每个分类附加最新文章的时间戳
foreach ($categories as $key => $category) {
    $post_args = array(
        'numberposts' => 1,
        'category' => $category->term_id,
        'post_status' => 'publish' // 仅取已发布的公开文章
    );
    $latest_post = get_posts($post_args);
    // 给分类对象新增最新文章时间属性,空分类赋值为0自动排到最后
    $categories[$key]->latest_time = !empty($latest_post) ? get_post_time('U', false, $latest_post[0]) : 0;
}

// 自定义排序:按最新文章时间倒序,更新时间越近的分类越靠前
usort($categories, function($a, $b) {
    return $b->latest_time - $a->latest_time;
});

// 遍历排序后的分类输出文章
foreach ($categories as $category) {
    $post_args = array(
        'numberposts' => 1,
        'category' => $category->term_id,
    );
    $posts = get_posts($post_args);
    foreach ($posts as $post) {
?>
<article <?php post_class('post-list animated fadeIn'); ?> role="article">
    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
        <figure class="eyecatch<?php if (!has_post_thumbnail()) : ?> noimg<?php endif; ?>">
            <?php the_post_thumbnail('home-thum'); ?>
            <?php archivecatname(); ?>
        </figure>

        <section class="entry-content cf">
            <h1 class="h2 entry-title"><?php the_title(); ?></h1>
            <div class="byline entry-meta vcard">
                <?php if (get_option('post_options_authordisplay', 'author_off') == 'author_on') : ?>
                <span class="writer name author"><?php echo get_avatar(get_the_author_meta('ID'), 30); ?><span class="fn"><?php the_author(); ?></span></span>
                <?php endif; ?>
            </div>
            <div class="description"><?php the_excerpt(); ?></div>
        </section>
    </a>
</article>
<?php get_template_part('loop'); ?>
<?php
    }
}
?>

核心调整说明

  • 新增了分类绑定最新文章时间戳的逻辑,替换了原有的固定按ID排序规则
  • 新增usort自定义排序方法,保证有新文章发布的分类自动上浮到最前
  • 可选添加了空分类过滤参数,可根据自身需求删除对应配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:45:03