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

WordPress Rewrite Rules设置特定分类固定链接后显示分类页而非单篇文章

问题排查与解决方法

核心错误原因

  • 重写规则数组存在重复键:两个规则都用了^Educational/([^/]+)/?$作为键,后者直接覆盖了前者,且被覆盖的规则里错误调用了不存在的$matches[2](该正则只有1个捕获组,只能取$matches[1]),导致单篇文章的路径匹配规则完全失效,WordPress会把/Educational/xxx/路径当成分类存档请求处理,所以返回文章列表。

修复步骤

  1. 清理重复的重写规则,删除错误的$new_rules['^Educational/([^/]+)/?$'] = 'index.php?name=$matches[2]';这行代码
  2. 可选优化:分类判断优先用分类ID而非分类名,避免分类名修改后规则失效;如果确定只判断第一个分类可以保留原有逻辑,建议增加判断分类别名更稳定
  3. 修改代码后,需要到WordPress后台【设置】-【固定链接】页面,直接点击保存更改(不需要修改任何参数),刷新重写规则缓存,否则修改不会生效

修正后的完整代码

function custom_permalink( $permalink, $post, $leavename ) {
    // 获取文章所属分类
    $category = get_the_category($post->ID); 
    if (  !empty($category) && $category[0]->cat_name == "Educational" ) {
        // 也可以换成用分类ID判断,更稳定:$category[0]->term_id == 61
        $permalink = trailingslashit( home_url('/Educational/'. $post->post_name .'/' ) );
    }
    return $permalink;
}
add_filter( 'post_link', 'custom_permalink', 10, 3);

function custom_rewrite_rules( $wp_rewrite ) {
    $new_rules = [];
    // 匹配Educational分类下的单篇文章
    $new_rules['^Educational/([^/]+)/?$'] = 'index.php?name=$matches[1]';
    // 匹配Educational分类列表页
    $new_rules['^Educational/?$'] = 'index.php?cat=61';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');

验证方法

修改并刷新重写规则后,先清掉网站缓存和浏览器缓存,分别访问:

  • Educational分类列表页/Educational/,确认返回该分类下的文章列表
  • 该分类下的单篇文章链接/Educational/文章别名/,确认返回单篇文章内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:24:04