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

如何在WordPress中实现将Custom Post Type追加到分类URL

解决自定义文章类型分类URL格式问题

要让分类链接和文章链接包含自定义文章类型前缀(比如custom_post),需要两步操作:修改重写规则+调整链接输出代码。

1. 添加重写规则到主题functions.php

在主题的functions.php文件末尾添加以下代码,注意把custom_post替换成你实际的自定义文章类型slug:

function custom_post_type_category_rewrite() {
    // 文章详情页规则:匹配 custom_post/分类slug/文章slug
    add_rewrite_rule(
        '^custom_post/([^/]+)/([^/]+)/?$',
        'index.php?category_name=$matches[1]&name=$matches[2]&post_type=custom_post',
        'top'
    );
    // 分类列表页规则:匹配 custom_post/分类slug
    add_rewrite_rule(
        '^custom_post/([^/]+)/?$',
        'index.php?category_name=$matches[1]&post_type=custom_post',
        'top'
    );
}
add_action('init', 'custom_post_type_category_rewrite');

添加后,进入WordPress后台「设置」→「固定链接」,直接点击「保存更改」(不需要修改设置),让重写规则生效。

2. 修改你的分类链接输出代码

把原代码中用get_category_link()生成链接的部分,替换成自定义构造的URL,确保包含自定义文章类型前缀:

原代码中的链接部分:

<a href="<?php echo get_category_link( $category->term_id ) ?>">

替换为:

<a href="<?php echo esc_url( home_url( '/' . $post_type . '/' . $category->slug . '/' ) ) ?>">

这样输出的分类链接格式就会是www.website/custom_post/分类slug/,点击分类后,里面的文章链接也会自动变成www.website/custom_post/分类slug/文章名称/。

额外注意

  • 确保你的自定义文章类型注册时,设置了has_archive为true,并且rewrite参数正确,例如:
    register_post_type('custom_post', array(
        // 其他参数...
        'rewrite' => array('slug' => 'custom_post', 'with_front' => false),
        'has_archive' => true,
    ));
    
  • 如果你的固定链接结构不是基于分类的,可能需要调整重写规则的匹配逻辑,但上述代码适用于大多数场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 23:00:29