wordpress 自定义路由及展示页
注册domain/test这个路由
wordpress 有重写url的方法,叫 add_rewrite_rule()。在function.php中加入如下代码段:
// 添加路由重写,每次修改完记得在wp-admin后台“设置”-》“固定链接”=》“保存”才能生效
add_action('init', 'theme_functionality_urls');
function theme_functionality_urls() {
add_rewrite_rule('^test','index.php?test=1','top');
}
这段代码的意思就是把domain?test=1改写成domain/test,top意思是把这个规则放到最前面。
响应domain/test这个请求
- 获取到这个test的值
add_action('query_vars', 'test_add_query_vars');
function test_add_query_vars($public_query_vars){
$public_query_vars[] = 'test';
return $public_query_vars;
}
这段代码的意思是在执行到query_vars这个钩子的时候,给$public_query_vars数组里面添加一个test字段,这个test字段就是当访问domain?test=1的时候的test的字段。当添加test到$public_query_vars之后,会检查每个请求url里是否包含test字段。
- 模板载入规则
//模板载入规则
add_action("template_redirect", 'test_template_redirect');
function test_template_redirect(){
global $wp;
global $wp_query;
$reditect_page = $wp_query->query_vars['test'];
if ($reditect_page == "1"){
include(TEMPLATEPATH.'/test/test.php');
die();
}
}
这段代码的意思是这样的,首先,这个TEMPLATEPATH是你的主题路径,连着/test/test.php相当于在你的主题目录下新建了一个test目录,test目录里有一个test.php文件。