WordPress修改固定链接后自动301重定向

我们使用wordpress做站时因这样或者那样的需要更改网站的固定链接,但是更改固定链接后搜索引擎还是收录的以前的网址,导致访问者访问时出现打不开页面的情况,我们把网站之前的链接做301重定向到我们新的链接,这样对搜索引擎和访问者页都好。

以前都是通过插件的方法来实现的,插件如果安装过多会影响wordpress的速度,现在我们直接通过代码的形式来进行301重定向。

$rewrite_config = array();
$rewrite_config['highpriority'] = true ;
$rewrite_config['rewrite'] = array();
$rewrite_config['oldstructure'] = "/%year%/%monthnum%/%postname%/";

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'] = "/%year%/%monthnum%/%postname%/";后面的/%year%/%monthnum%/%postname%/修改成你自己以前的固定链接格式,然后将这段代码加入到主题的function.php中,之后设置新的固定链接格式就行了。

版权声明:
作者:小陈
链接:https://www.wolongju.com/archives/1587
来源:卧龙居
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>