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

如何在WordPress中仅移除特定分类文章的URL分类前缀

解决WordPress指定分类文章移除分类前缀的问题

你之前的代码只改了前台显示的URL,但没配置服务器重写规则,也没让WordPress正确识别新URL,所以才会404。下面是完整的代码方案,分三部分搞定:

1. 修改文章链接的显示格式

替换你之前的pre_post_link过滤函数,确保catname1分类的文章去掉/%category%/前缀:

function custom_remove_category_prefix_from_permalink( $permalink, $post ) {
    // 只处理文章类型
    if ( $post->post_type !== 'post' ) {
        return $permalink;
    }

    // 获取文章所属分类,优先取主分类
    $categories = get_the_category( $post->ID );
    if ( empty( $categories ) ) {
        return $permalink;
    }

    // 按WordPress默认逻辑取主分类
    usort( $categories, '_usort_terms_by_ID' );
    $primary_category = apply_filters( 'post_link_category', $categories[0], $categories, $post );

    // 替换成你的目标分类slug:catname1
    if ( $primary_category->slug === 'catname1' ) {
        // 移除分类前缀部分
        return str_replace( '%category%/', '', $permalink );
    }

    return $permalink;
}
add_filter( 'pre_post_link', 'custom_remove_category_prefix_from_permalink', 10, 2 );

2. 添加自定义重写规则

告诉服务器:访问example.com/postname时,要把这个路径解析成对应文章的请求:

function custom_add_rewrite_rules() {
    // 添加重写规则,匹配根目录下的文章名,指向文章查询
    add_rewrite_rule(
        '^([^/]+)/?$',
        'index.php?name=$matches[1]',
        'top' // 设为最高优先级,避免和其他规则冲突
    );
}
add_action( 'init', 'custom_add_rewrite_rules' );

3. 处理重名冲突(可选)

如果你的网站有和文章同名的页面(Page),可以加这段代码让WordPress优先解析页面,找不到再找catname1的文章:

function custom_adjust_query_for_permalink( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->get( 'name' ) ) {
        // 检查是否存在同名页面
        $page = get_page_by_path( $query->get( 'name' ) );
        if ( $page ) {
            $query->set( 'post_type', 'page' );
        } else {
            // 只查询catname1分类的文章,避免其他分类文章被误匹配
            $query->set( 'category_name', 'catname1' );
        }
    }
}
add_action( 'pre_get_posts', 'custom_adjust_query_for_permalink' );

操作步骤

  1. 把上面的代码贴到主题的functions.php里,或者自己建个简单的自定义插件
  2. 登录WordPress后台,进设置→固定链接,直接点「保存更改」(不用改任何设置,这步是刷新重写规则)
  3. 测试catname1分类的文章,确认URL是example.com/postname且能正常打开,其他分类的文章保持原结构就行

为啥之前的代码会404?

你之前的代码只改了链接显示的样子,但服务器还是按照原来的/%category%/%postname%规则解析请求。当你访问example.com/postname时,服务器不知道这个路径对应哪篇文章,自然返回404。加了重写规则后,服务器才会把根目录的字符串当作文章名传给WordPress,再找到对应的文章。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:37:46