将旧的自定义帖子 URL 重定向到新的 WordPress URL

Redirect old custom Posts URL to new WordPress URL

简而言之,我将旧的自定义站点转换为新的 WordPress 站点,域保持不变,我使用 PHP 将数千篇旧文章及其评论插入 WordPress 数据库,保持相同的 ID 序列,这意味着如果旧的 link 是:

www.mysite.com/index.php?id=11058

www.mysite.com/index.php?category=12

比新的link有:

www.mysite.com/?p=11058

www.mysite.com/?cat=12

一切都做得很好,唯一的问题是我不想失去旧的背影link,我想用PHP重定向,例如:

    if (isset($_GET['old_id'])) {  $id=$_GET['old_id']; $Wordpress_post_id = $id; }

如何在 WordPress 中使用此代码?这种方法更好还是通过 .htaccess 重定向?或者有没有比这两种更好的方法?

我会在 template_redirect 中这样做:

This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.

add_action(
    'template_redirect',
    static function() {

        if(!isset($_GET['old_id'])){
            return;
        }

        // Do custom look up here, possibly get_posts()

        // Once you determine where to go, use wp_safe_redirect with the appropriate code (probably 301)
        // https://developer.wordpress.org/reference/functions/wp_safe_redirect/

        // Also possibly use get_permalink() to find the canonical link for the object
        // https://developer.wordpress.org/reference/functions/get_permalink/
    }
);

不幸的是,“自定义内容”实际上取决于您存储内容的方式。是 post 元,你手动插入 post ID,是自定义查找 table?

如果它是遗留 ID 到 PostID 的真实映射,您甚至可以通过简单的规则使用 Redirection 等插件。

由于您提到(并标记).htaccess,您可以在 .htaccess 文件的顶部(在 # BEGIN WordPress 注释标记之前)这样做:

# Redirect "/index.php?id=<number>" to "/?p=<number>"
RewriteCond %{QUERY_STRING} ^id=(\d+)
RewriteRule ^index\.php$ /?p=%1 [R=301,L]

# Redirect "/index.php?category=<number>" to "/?cat=<number>"
RewriteCond %{QUERY_STRING} ^category=(\d+)
RewriteRule ^index\.php$ /?cat=%1 [R=301,L]

其中 %1 在这两种情况下都是对前面 CondPattern 中捕获组的反向引用。 IE。 idcategory URL 参数的值。

使用 302(临时)重定向进行测试以避免缓存问题。

我最近不得不做同样的事情。我重组了一个站点并将结构从根目录(和所有目录结构)移动到 blog 文件夹。我在WordPress上试验了几种方法,分析了日志中的问题等,实现了下面的方法。

首先我创建了每个页面、文章等的列表

然后我在站点根目录中创建了一个 .htaccess 文件。

在我下面的示例中,我显示了一页的重定向,但有两个条目(尾部斜杠或没有)。底部处理文件和目录等

我的 .htaccess 大约有 600 行长。我没有注意到重定向有任何性能问题。

注意:我使用 302 进行重定向,如果您的重定向是永久性的,请考虑使用 301。

<IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
  </IfModule>

  RewriteEngine On

  RewriteRule ^aboutme$ https://www.example.com/blog/aboutme/ [L,R=302]
  RewriteRule ^aboutme/$ https://www.example.com/blog/aboutme/ [L,R=302]

  # Handle Authorization Header
  RewriteCond %{HTTP:Authorization} .
  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Redirect Trailing Slashes If Not A Folder...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} (.+)/$
  RewriteRule ^ %1 [L,R=301]

  # Send Requests To Front Controller...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [L]
</IfModule>