前面一篇教程我們介紹了 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/ 就能看到前面圖示的效果了。