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

WordPress无分类URL重定向至带分类URL的非插件方案求助

WordPress 旧URL到带分类URL的301重定向方案

原代码问题分析

你之前的代码无效核心原因是判断逻辑错误:

  • 错误对比home_url(add_query_arg(array()))与构造的新URL,无法正确识别旧格式URL,甚至可能触发循环重定向
  • 未检查当前请求的URL是否属于需要重定向的旧格式(仅含文章slug)

方案一:修正后的PHP钩子重定向

先在WordPress后台「设置→固定链接」中,将结构改为/%category%/%postname%/,确保新发布的文章自动使用带分类的URL。然后将以下代码添加到主题的functions.php中:

add_action('template_redirect', 'custom_old_to_new_redirect');
function custom_old_to_new_redirect() {
    if (is_single() && !is_admin()) {
        global $post;
        $current_uri = trim($_SERVER['REQUEST_URI'], '/');
        $post_slug = $post->post_name;

        // 仅当当前URL是旧格式(仅含文章slug)时执行重定向
        if ($current_uri === $post_slug) {
            $categories = get_the_category($post->ID);
            if (!empty($categories)) {
                $cat_slug = $categories[0]->slug;
                $new_url = home_url("/{$cat_slug}/{$post_slug}/");
                wp_redirect($new_url, 301);
                exit;
            }
        }
    }
}

说明

  • 仅对旧格式的单文章URL生效,避免循环重定向
  • 使用301永久重定向,完全符合SEO权重传递要求
  • 取文章的第一个分类作为URL中的分类部分;若需指定主分类,可替换为通过自定义字段或SEO插件(如Yoast)获取主分类ID,再用get_category($cat_id)获取slug

方案二:利用Rewrite规则(更高效)

重写规则在服务器层面处理,比PHP钩子更早执行,性能更优。将以下代码添加到functions.php:

// 添加重写规则,匹配旧格式URL
add_action('init', 'custom_add_rewrite_rule');
function custom_add_rewrite_rule() {
    add_rewrite_rule(
        '^([^/]+)/?$',
        'index.php?name=$matches[1]&old_url=1',
        'top'
    );
}

// 注册自定义查询变量
add_filter('query_vars', 'custom_add_query_var');
function custom_add_query_var($vars) {
    $vars[] = 'old_url';
    return $vars;
}

// 处理重定向逻辑
add_action('template_redirect', 'custom_rewrite_redirect');
function custom_rewrite_redirect() {
    if (get_query_var('old_url') && is_single() && !is_admin()) {
        global $post;
        $categories = get_the_category($post->ID);
        if (!empty($categories)) {
            $cat_slug = $categories[0]->slug;
            $post_slug = $post->post_name;
            $new_url = home_url("/{$cat_slug}/{$post_slug}/");
            wp_redirect($new_url, 301);
            exit;
        }
    }
}

注意事项

  1. 添加代码后,必须到后台「设置→固定链接」页面点击「保存更改」,刷新WordPress的重写规则
  2. 若使用缓存插件,需清除缓存以确保新规则生效
  3. 测试时可通过浏览器开发者工具查看网络请求状态码,确认返回301

额外SEO提示

  • 确保每个旧URL对应唯一的新URL,避免重复内容问题
  • 若文章有多个分类,建议指定一个主分类作为URL中的分类部分,保持URL一致性
  • 可在Google Search Console中提交URL更改,加快搜索引擎索引更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:31:03