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

如何为WordPress特定自定义文章类型定制URL结构

解决WordPress自定义文章类型URL自定义(/information/yyyy/mm/dd/post_id)的404问题

问题原因

你之前的代码仅修改了前端显示的文章链接,但WordPress重写规则中没有对应的解析逻辑,服务器无法识别该URL对应的内容,因此返回404错误。需要同时调整链接生成逻辑和添加重写规则。

解决方案步骤

1. 修正文章链接生成逻辑

更新post_type_link过滤器函数,确保生成符合要求的URL,同时仅处理已发布的文章:

function custom_permalink_structure($permalink, $post) {
    // 仅针对已发布的information类型文章修改链接
    if ($post->post_type === 'information' && $post->post_status === 'publish') {
        $publish_date = date('Y/m/d', strtotime($post->post_date));
        $permalink = home_url("/information/{$publish_date}/{$post->ID}/");
    }
    return $permalink;
}
add_filter('post_type_link', 'custom_permalink_structure', 10, 2);

2. 添加URL重写规则

添加重写规则,告知WordPress如何解析/information/yyyy/mm/dd/post_id格式的URL:

function custom_information_rewrite_rules() {
    // 匹配日期+ID的URL结构,设置top优先级避免与information页面冲突
    add_rewrite_rule(
        'information/([0-9]{4})/([0-9]{2})/([0-9]{2})/([0-9]+)/?$',
        'index.php?post_type=information&p=$matches[4]',
        'top'
    );
}
add_action('init', 'custom_information_rewrite_rules');

3. 保留现有分页重写规则

你之前添加的分页规则可继续保留,无需修改:

add_rewrite_rule( 'information/page/([0-9]+)/?$', 'index.php?pagename=information&paged=$matches[1]', 'top' );

4. 刷新重写规则

代码修改完成后,必须刷新WordPress重写规则才能生效:

  • 登录WordPress后台
  • 进入「设置」→「固定链接」
  • 直接点击「保存更改」(无需修改任何设置)

关键说明

  • 重写规则的top优先级确保WordPress优先解析文章URL,避免与slug为information的页面冲突
  • 仅处理publish状态的文章,避免草稿、待审等状态的文章生成无效链接
  • 刷新重写规则是必不可少的步骤,否则新规则不会生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:20:16