欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress后台修改固定链接后如何设置301重定向?

作者 : 自学哈 本文共1704个字,预计阅读时间需要5分钟 2022-11-26 共107人阅读
也想出现在这里? 联系我们

以前网站的固定链接结构是是/%year%/%monthnum%/%postname%/,这样看起来又不直观又长的,现在是/%postname%.html看起来短了很多,也很直观,修改固定链接后,如果没有做好301重定向,跳转到新地址会产生404页面,那么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中,然后设置成新的固定链接格式就搞定了。

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress后台修改固定链接后如何设置301重定向?
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号