本文遵守署名 4.0 国际 (CC BY 4.0)协议
技术宅之前的网址固定链接样式是/%postname%.html
,后来因为其他原因,技术宅将固定链接样式换成了/%post_id%
,但是因为技术宅站点被搜索引擎收录了,新建的文章没问题,但是用户从搜索引擎收录的旧链接访问就会场产生404,这样不利于站点优化。有修改网站固定链接后已收录页面404的站长可以使用以下代码:
$rewrite_config = array(); $rewrite_config['highpriority'] = true ; $rewrite_config['rewrite'] = array(); $rewrite_config['oldstructure'] = "/%postname%.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'] = "/%postname%.html";
里面的/%postname%.html
修改成你自己的旧的固定链接。
然后将这段代码加入到你的当前主题的function.php
中,然后清除PHP缓存,已经确认固定链接已修改即可!
本文由转载小助手发布