前面一篇教程我們介紹了 WordPress url 重寫是怎麼工作的,這一篇教程我們來個小例子,加深對 WordPress url 重寫的認識。
今天的例子要做到的 (這是 WordPress 自定義會員系統的雛形哦):
以預設的 twenty ten 主題為例,我們現在預設主題中新建一個 user 資料夾,資料夾中新增一個 php 檔案,裡面的程式碼為:
- <?php
- /*********使用者歡迎頁面************/
- get_header(); //載入頭部檔案
- if( !is_user_logged_in()) { //判斷使用者是否登入
- echo '<div style="text-align:center; margin:40px;"> 訪客您好, 請先登入。</div>';
- }else{
- global $current_user;
- get_currentuserinfo();
- $uname = $current_user->user_nicename;
- echo '<div style="text-align:center; margin:40px;"><span style="color:red;">';
- echo $uname; //輸出使用者名稱
- echo '</span> 您好,歡迎登陸...</div>';
- }
- get_footer(); //載入底部檔案
- ?>
這個檔案透過判斷使用者分別輸出一句歡迎語句。效果圖 (點選圖片檢視大圖)

實際操作:
一、新增翻譯規則。首先我們前面介紹了 url 的翻譯規則,我們要往翻譯規則中新增一條自己的翻譯規則,請往你的 twenty ten 主題的 functions.php 檔案新增下列程式碼:
- add_action('generate_rewrite_rules', 'ashu_rewrite_rules' );
- /**********重寫規則************/
- function ashu_rewrite_rules( $wp_rewrite ){
- $new_rules = array(
- 'my-account/?$' => 'index.php?my_custom_page=hello_page',
- ); //新增翻譯規則
- $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
- //php 陣列相加
- }
前面我們關於過濾器的教程中提到了過濾器的用法及用處,重寫規則位於一個陣列中,我們使用過濾器鉤子 generate_rewrite_rules 來更改這個規則陣列,往裡面新增內容,即達到了我們的目的。這個時候,我們訪問地址 (作者本機測試地址):localhost/newtheme/my-account/就會被翻譯成 index.php?my_custom_page=hello_page 。
翻譯規則介紹:
- 'my-account/?$' => 'index.php?my_custom_page=hello_page',
- /*
- 前面應該是一個正規表示式,my-account/?$ 只能匹配 my-account/ 如果你訪問的地址是 localhost/newtheme/my-account/aa 則不能匹配
- */
注意到翻譯後的地址中有一個 my_custom_page,以及我們上一篇教程中列出來的 author_name,這想當於一個變數。比如我們訪問 index.php?author_name=admin,透過這個變數的判斷,載入 WordPress 的作者模板,然後根據這個變數的值 admin,顯示使用者名稱為 admin 的內容。實際上這些變數儲存在一個全域性變數 $public_query_vars,這是一個陣列,只有陣列中存在的變數才能被正確翻譯,所以我們要往這個變數中新增元素。
二、新增 $public_query_vars
- /*******新增 query_var 變數***************/
- add_action('query_vars', 'ashu_add_query_vars');
- function ashu_add_query_vars($public_query_vars){
- $public_query_vars[] = 'my_custom_page'; //往陣列中新增新增 my_custom_page
- return $public_query_vars;
- }
三、新增模板載入規則。
- //模板載入規則
- add_action("template_redirect", 'ashu_template_redirect');
- function ashu_template_redirect(){
- global $wp;
- global $wp_query, $wp_rewrite;
- //查詢 my_custom_page 變數
- $reditect_page = $wp_query->query_vars['my_custom_page'];
- //如果 my_custom_page 等於 hello_page,則載入 user/helloashu.php 頁面
- //注意 my-account/被翻譯成 index.php?my_custom_page=hello_page 了。
- if ($reditect_page == "hello_page"){
- include(TEMPLATEPATH.'/user/helloashu.php');
- die();
- }
- }
不要高興的太早,到了這裡還沒完成呢,現在只新增了程式碼,但是重寫規則還沒儲存到資料庫。
四、更新重寫規則
- /***************啟用主題更新重寫規則***********************/
- add_action( 'load-themes.php', 'frosty_flush_rewrite_rules' );
- function frosty_flush_rewrite_rules() {
- global $pagenow, $wp_rewrite;
- if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) )
- $wp_rewrite->flush_rules();
- }
OK,到了這裡,到後臺重新啟用你的主題,然後訪問地址: 你的 網址 my-account/ 就能看到前面圖示的效果了。