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

如何仅修改自定义文章类型固定链接?解决404错误问题

自定义文章类型Permalink修改后出现404的解决方法

核心解决步骤

1. 刷新WordPress固定链接规则

这是最容易被忽略的关键操作:

  • 登录WordPress后台,进入设置 → 固定链接页面
  • 无需修改任何选项,直接点击保存更改按钮。这会触发WordPress更新服务器上的重写规则(.htaccess文件),让新的permalink规则生效。

2. 调整代码中的问题

你的代码存在两处需要优化的地方,修改后的完整代码如下:

function add_custom_post_type(){
  register_post_type(
      'carrot',
      [
          'label' => 'Carrot',
          'public'        => true,
          'has_archive'   => true,
          'menu_position' => 5,
          'menu_icon'     => 'dashicons-carrot',
          'hierarchical' => true,
          'supports' => [
              'title',
              'editor',
              'page-attributes'
          ],
          // 添加rewrite配置,避免和默认规则冲突
          'rewrite' => [
              'slug' => 'carrot',
              'with_front' => false,
              'feeds' => false,
              'pages' => false
          ]
      ]
  );
}
add_action('init', 'add_custom_post_type');

// 调整过滤器优先级为10,确保覆盖默认链接处理
add_filter('post_type_link', 'my_post_type_link', 10, 2);
add_filter('rewrite_rules_array', 'my_rewrite_rules_array');

function my_post_type_link($link, $post){
  if($post->post_type === 'carrot'){
    return home_url('/carrot/'.$post->ID);
  } else {
    return $link;
  }
}

function my_rewrite_rules_array($rules){
  $new_rule = array(
    'carrot/([0-9]+)/?$' => 'index.php?post_type=carrot&p=$matches[1]'
  );
  // 自定义规则放在数组头部,优先匹配
  return $new_rule + $rules;
}

代码调整说明:

  • 添加rewrite参数:注册自定义文章类型时明确配置重写规则的基础,禁用默认的slug生成逻辑,避免和你自定义的ID规则冲突;with_front设为false可以防止主固定链接的前缀(如博客目录)被加到carrot路径前。
  • 调整过滤器优先级:把post_type_link的优先级从1改为10,确保你的自定义链接逻辑在WordPress默认处理之后执行,正确覆盖默认的permalink。
  • 规则顺序:将自定义的重写规则放在数组最前面,保证WordPress优先匹配你的ID规则,而不是默认的基于标题的slug规则。

完成以上两步后,重新访问自定义文章类型的页面,404问题应该就能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:21:27