如何将Permalink从/%category%/%postname%/改为/%category%/%postname%-%post_id%/并配置重定向?
解决WordPress固定链接变更后的重定向问题
不管用插件还是写函数都能解决,两种方案给你参考:
一、用Redirection插件配置规则
- 先去WordPress后台「设置」→「固定链接」,把结构改成
/%category%/%postname%-%post_id%/,保存设置。 - 安装并激活Redirection插件,进入插件的「添加新重定向」页面。
- 设置规则:
- 源URL:填写正则表达式
^/([^/]+)/([^/]+)/$ - 目标URL:填写
/$1/$2-%id%/ - 匹配类型:选择「正则表达式」
- 勾选「永久重定向(301)」后保存规则。
- 源URL:填写正则表达式
插件会自动识别旧链接对应的文章,把%id%替换成文章ID,完成重定向。
二、用代码函数实现(更轻量化)
如果不想依赖插件,直接在主题的functions.php文件末尾添加以下代码:
add_action('template_redirect', 'custom_permalink_redirect'); function custom_permalink_redirect() { global $wp; $current_path = $wp->request; // 匹配旧固定链接格式:category/postname/ if (preg_match('#^([^/]+)/([^/]+)/$#', $current_path, $matches)) { $cat_slug = $matches[1]; $post_slug = $matches[2]; // 根据分类和文章slug查找对应文章 $target_post = get_posts([ 'name' => $post_slug, 'category_name' => $cat_slug, 'post_type' => 'post', 'numberposts' => 1 ]); if ($target_post) { $new_url = get_permalink($target_post[0]->ID); wp_redirect($new_url, 301); exit; } } }
这段代码会在页面加载时检查请求路径,匹配旧格式就自动跳转到对应的新固定链接,301永久重定向对SEO更友好。
注意:先在后台设置好新的固定链接结构,再添加这段代码。
内容的提问来源于stack exchange,提问作者W1ns
相关产品推荐
相关产品推荐

