以前小站的固定鏈接好不人性化,結(jié)構(gòu)是/%year%/%monthnum%/%postname%/,這樣看起來(lái)又不直觀又長(zhǎng)的,今天做了一個(gè)301重定向,然后修改了新的固定鏈接,現(xiàn)在的固定鏈接格式是/%postname%.html,這樣看起來(lái)短了好多,也直觀了好多,
不過(guò)小站已經(jīng)被搜索引擎收錄了好多,以前的地址都無(wú)法訪問(wèn)了,所以要做好301重定向,跳轉(zhuǎn)到新的固定鏈接所生成的地址中去.要不然都是404就悲劇了.下面貼出解決辦法
$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中,然后設(shè)置成新的固定鏈接格式就搞定了.