Rewrite API

WordPress Rewrite API

一篇文章或是產品訊息, 如果有一個簡單乾淨的網址, 則不管貼到 facebook 或是 討論區, 方便好看, 在 wordpress 的 functions.php 中, 加入以下程式碼:

// Add the rewrite rule – 增加 rewrite_rule, 必須在 init 時

add_action( ‘init’, ‘anson_add_rules’ );
function anson_add_rules() {
add_rewrite_rule( ‘my_billboard/?([^/]*)’,
‘index.php?pagename=my-page&list_type=$matches[1]‘, ‘top’ );
}

// list_type是自己定義的參數, 也可以是product id, 用來辨識產品.
// 必須將 list_type 加入query_vars, 讓 wordpress 認得它.

add_filter( ‘query_vars’, ‘anson_add_query_var’ );
function anson_add_query_var( $vars ) {
$vars[] = ‘list_type’;
return $vars;
}

之後就可以使用這樣的網址:

http://xxxxxx.xxxx.xxx/my_billboard/new-product

wordpress 會把 new-product 這個字串 帶入 index.php?pagename=my-page&list_type=$matches[1]     中的 list_type

備註: 如果沒有效用, 請先瀏覽一下後台的 固定網址頁面  /wp-admin/options-permalink.php  , 瀏覽這頁 可以清 cache  (flush_rules).


技術細節 (英文) :  http://codex.wordpress.org/Rewrite_API


分享這篇文章的網址這篇文章的網址(可分享到FB、LINE):

用LINE分享給朋友: