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

求助:WordPress中含数字的Year类文档标题排序不符合预期

修复文档标题排序问题的方案

修改你的usort回调逻辑,调整年份排序方向和同年份标题的排序规则,即可得到期望的结果:

$documents = get_posts(array(
    'post_type' => 'maps_document',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'maps_document_category',
            'terms' => $category->slug,
            'field' => 'slug'
        )
    )
));

usort($documents, function($a, $b) {
    preg_match('/^Year (\d+)/', $a->post_title, $a_matches);
    preg_match('/^Year (\d+)/', $b->post_title, $b_matches);
    $a_year = $a_matches[1] ?? 0;
    $b_year = $b_matches[1] ?? 0;

    if ($a_year !== $b_year) {
        // 按年份降序排列(大年份在前)
        return $b_year - $a_year;
    } else {
        // 同一年份时,按标题反向字母顺序排列
        return strcasecmp($b->post_title, $a->post_title);
    }
});

修改说明

  1. 年份排序方向调整:原代码中$a_year - $b_year会让小年份标题排在前面,改为$b_year - $a_year后,大年份(如Year 10)会优先排列。
  2. 同年份标题排序反转:原代码用strcasecmp($a->post_title, $b->post_title)按正序字母排列,改为strcasecmp($b->post_title, $a->post_title)后,同一年份下字母顺序靠后的标题(如Year 9 Handbook)会排在字母顺序靠前的(如Year 9 Booklist)之前,匹配你的期望输出。

验证结果

修改后排序结果将与你期望的完全一致:

Enrolment 2023
Enrolment Timeline for Year 7
Instrumental Music – Expressions of Interest Form and Payment 2023
Instrumental Music – Re-Enrolment Form and Payment 2023
Prospectus 2023
Senior School Handbook
Uniform List 2022
Year 10 & VCE Booklist 2023
Year 9 Handbook
Year 9 Booklist 2023
Year 8 Booklist 2023
Year 7 Booklist 2023
Year 6-7 Non Government School Placement Pack

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:43:08