WordPress更换固定链接后旧链接的处理
在搭建wordpress的前期,如果想更换固定链接还来得及,搜索引擎的收录很少,所以处理起来会很简单。
但是建站已经很久了,搜索引擎收录的内容也相当多,直接更换固定链接后,原来的链接就会变成404
这很不符合我们的需求。我们需要新的固定链接的同时将就链接转向到新的连接中。
wordpress有专门的路由,所以我们需要修改系统的路由。
修改路由有使用插件的、修改主题的function文件的,在这里我选择的是修改主题中的function文件,wordpress中使用的插件越少越好。如果你想用插件解决,你可以使用wp-permalinks-migration 下载地址
原理:
在提交修改固定链接时,将旧的路由规则同时添加到系统中;打开文章页面时,判断当前进入的链接是否是旧链接,如果是旧链接,就用301转跳到新地址中。
代码:
$rewrite_config = array();
$rewrite_config['highpriority'] = true ;
$rewrite_config['rewrite'] = array();
$rewrite_config['oldstructure'] = "/%year%/topic-%post_id%.html";
function wpdaxue_pm_the_posts($post) {
global $wp;
global $wp_rewrite;
global $rewrite_config;
$rewrite_config['rewrite'] = $wp_rewrite->generate_rewrite_rule($rewrite_config['oldstructure'], false, true, true, true);
if ($post != NULL && is_single() && $rewrite_config['oldstructure'] != $wp_rewrite->permalink_structure) {
if (array_key_exists($wp->matched_rule, $rewrite_config['rewrite'])) {
// ok, we need to generate a 301 Permanent redirect here.
header("HTTP/1.1 301 Moved Permanently", TRUE, 301);
header('Status: 301 Moved Permanently');
$permalink = get_permalink($post[0]->ID);
if (is_feed()) {
$permalink = trailingslashit($permalink) . 'feed/';
}
header("Location: ". $permalink);
exit();
}
}
return $post;
}
function wpdaxue_pm_post_rewrite_rules($rules) {
global $wp_rewrite;
global $rewrite_config;
$oldstruct = $rewrite_config['oldstructure'];
if ($oldstruct != NULL && $oldstruct != $wp_rewrite->permalink_structure) {
$rewrite_config['rewrite'] = $wp_rewrite->generate_rewrite_rule($oldstruct, false, true, true, true);
if ($rewrite_config ['highpriority'] == true) {
return array_merge($rewrite_config['rewrite'], $rules);
} else {
return array_merge($rules, $rewrite_config['rewrite']);
}
}
return $rules;
}
add_filter('the_posts', 'wpdaxue_pm_the_posts', 20);
add_filter('post_rewrite_rules', 'wpdaxue_pm_post_rewrite_rules');
$rewrite_config['oldstructure']这个就是旧的固定链接格式,修改成你之前的固定链接,保存。
然后到固定链接页面修改新的固定链接,打开旧的链接测试是否正常。
又少了一个插件,真好。
【声明】本文 WordPress更换固定链接后旧链接的处理 为柠之漠然原创文章,转载请注明出自
枫之落叶
并保留本文有效链接:https://blog.shiniv.com/2013/12/wordpress-permalinks-modify-oldstructure/ , 转载请保留本声明!
不错,值得收藏分享!