之前本博客固定链接格式:/a/%category%/%post_id%.html
网址长度对于SEO的影响,如果相对较长是存在一定的负面影响因子,这里我们尽量建议大家使用相对较短的网址!
现在改成:/%post_id%.html
改前:https://www.hongke120.com/a/js/17663.html
改后效果:https://www.hongke120.com/17663.html
为避免之前文章内的链接和搜索引擎收录的链接失效,我们将之前的链接301跳转到新链接
实现收录的链接正常打开,同时文章内容不变!
wordpress更改固定连接URL后做301重定向到新的URL,把如下代码放到模板所在目录的functions.php里即可:
/** * 更改内页url规则后,做内页301重定向到新url * @author albert * @date 2021.08.02 */ $rewrite_config = array(); $rewrite_config['highpriority'] = true ; $rewrite_config['rewrite'] = array(); $rewrite_config['oldstructure'] = "/%category%/%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'] = "/%category%/%post_id%.html";里面的固定链接改成自己之前的,然后再去后台设置新的固定链接即可!