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

WordPress固定链接变更后旧地址重定向至新地址的解决方案咨询

WordPress旧固定链接重定向到新格式的解决方案

方法一:通过主题functions.php添加重定向代码

在当前主题的functions.php文件末尾添加以下代码,它会自动检测访问的URL是否为旧格式(无作者前缀的单篇文章链接),匹配成功后跳转至带作者前缀的新链接:

add_action('template_redirect', 'old_post_slug_to_author_post_redirect');
function old_post_slug_to_author_post_redirect() {
    global $wp;
    $current_url = home_url($wp->request);
    
    // 排除后台、静态页面、分类/标签等非文章页面
    if (is_admin() || is_page() || is_archive() || is_home() || is_search()) {
        return;
    }
    
    $post_slug = $wp->request;
    $post = get_page_by_path($post_slug, OBJECT, 'post');
    
    if ($post) {
        $author = get_user_by('id', $post->post_author);
        $new_url = home_url('/' . $author->user_nicename . '/' . $post_slug . '/');
        
        // 301永久重定向(利于SEO)
        wp_redirect($new_url, 301);
        exit;
    }
}

注意事项:

  • 修改主题文件前请备份,避免操作失误导致网站故障
  • 若使用子主题,建议将代码添加到子主题的functions.php,防止主题更新时代码丢失
  • 301为永久重定向,对SEO友好,请勿改为302临时重定向

方法二:Apache服务器下通过.htaccess配合PHP脚本(可选)

如果你的服务器是Apache,可通过以下方式实现重定向:

  1. 在网站根目录创建redirect-old-posts.php文件,内容如下:
<?php
require_once('wp-load.php');

$post_slug = $_GET['slug'];
$post = get_page_by_path($post_slug, OBJECT, 'post');

if ($post) {
    $author = get_user_by('id', $post->post_author);
    $new_url = home_url('/' . $author->user_nicename . '/' . $post_slug . '/');
    wp_redirect($new_url, 301);
} else {
    // 找不到对应文章时跳转到404页面
    wp_redirect(home_url('/404/'), 404);
}
exit;
?>
  1. 在.htaccess中WordPress默认Rewrite规则之前添加以下代码:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ redirect-old-posts.php?slug=$1 [L]

注意事项:

  • 确保.htaccess文件权限正确,服务器可正常读取
  • 若WordPress安装在子目录,需调整RewriteRule的路径

验证方式

添加代码后,直接访问旧格式文章链接(如https://yourdomain.com/old-post-slug),应自动跳转至https://yourdomain.com/author-slug/old-post-slug/,浏览器网络状态码需显示301。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:33:01