由於網站
SEO 在大家心中都是非常重要,現在製作網站也都考慮了很多 SEO 的問題,其中一個功能就是可不可以自訂網址,Wordpress 很早之前就支援了此功能,站長我呢,在創站的時候使用
blog.wu-boy.com/2011/02/17/2542,為了使搜尋引擎更可以快速找到本站,所以打算將網址改成
blog.wu-boy.com/2011/02/php-codeigniter-google-url-shortener-api-library/,在後台 Permalink Settings 可以自訂部落格網址,將網址格式改成
/%year%/%monthnum%/%postname%/,可是改了之後,之前搜尋引擎及別人引用的網址就會變成
404 NOT Found,為瞭解決此問題,必須寫一支 Mapping Url 程式,讓之前的舊網址轉到新網址,剛好在
Roga Blog 找到一篇
加強部落格的 SEO,提供了轉換的 plugin,底下是該程式碼:
< ?php
/*
Plugin Name: roga's url hotfix
Plugin URI: http://blog.roga.tw/2011/02/%E5%8A%A0%E5%BC%B7%E9%83%A8%E8%90%BD%E6%A0%BC%E7%9A%84-seo/
Description: redirect http requests.
Version: 0.1
Author: roga
Author URI: http://blog.roga.tw
License: GPL v2
*/
function roga_wrap()
{
GLOBAL $wpdb;
$request_uri = getenv('REQUEST_URI');
$array = explode('/', $request_uri);
$status = TRUE;
foreach($array as $row)
{
if( ! is_numeric($row) && ! empty($row)) $status = FALSE;
}
if(count($array) != 5 || $status != TRUE)
return NULL;
$post_id = (int) $array[4]; // http://blog.roga.tw/2011/02/16/2484
$wp_result = $wpdb->get_row("SELECT `post_type`, `post_name`, `post_date` FROM `$wpdb->posts` WHERE `ID` = $post_id ");
if( ! isset($wp_result))
return NULL;
$post_type = $wp_result->post_type;
$post_name = $wp_result->post_name;
$post_date = $wp_result->post_date;
if($post_type == 'revision')
return NULL;
$time = strtotime($post_date);
$year = date('Y', $time);
$month = date('m', $time);
// old: /%year%/%monthnum%/%day%/%post_id%
// new: /%year%/%monthnum%/%postname%/
$new_request_uri = "/$year/$month/$post_name";
$http_host = getenv('HTTP_HOST');
$logfile = WP_CONTENT_DIR . "/cache/wp-roga-redirect.log";
if(file_exists($logfile))
file_put_contents($logfile, sprintf("[%s] %s -> %s / %s " . PHP_EOL, date_i18n("Y-m-d H:i:s"), $request_uri, urldecode($new_request_uri), getenv('HTTP_USER_AGENT')), FILE_APPEND);
header("Status: 301 Moved Permanently");
header("Location: http:/$http_host$new_request_uri");
exit();
}
add_action('init', 'roga_wrap');
Continue reading “WordPress plugin 加強網址 SEO”