您实际上是在尝试创建一个“假”页面,而不必在WordPress数据库中创建物理页面,为此,您需要自定义重写规则。
有关更多详细信息,请参见我的回答:Setting a custom sub-path for blog without using pages?
快速概述:
步骤1:设置自定义重写规则
add_action(\'init\', \'fake_page_rewrite\');
function fake_page_rewrite(){
global $wp_rewrite;
//set up our query variable %test% which equates to index.php?test=
add_rewrite_tag( \'%test%\', \'([^&]+)\');
//add rewrite rule that matches /test
add_rewrite_rule(\'^test/?\',\'index.php?test=test\',\'top\');
//add endpoint, in this case \'test\' to satisfy our rewrite rule /test
add_rewrite_endpoint( \'test\', EP_PERMALINK | EP_PAGES );
//flush rules to get this to work properly (do this once, then comment out)
$wp_rewrite->flush_rules();
}
步骤2:在匹配查询变量时正确地包含模板文件
add_action(\'template_redirect\', \'fake_page_redirect\');
function fake_page_redirect(){
global $wp;
//retrieve the query vars and store as variable $template
$template = $wp->query_vars;
//pass the $template variable into the conditional statement and
//check if the key \'test\' is one of the query_vars held in the $template array
//and that \'test\' is equal to the value of the key which is set
if ( array_key_exists( \'test\', $template ) && \'test\' == $template[\'test\'] ) {
//if the key \'test\' exists and \'test\' matches the value of that key
//then return the template specified below to handle presentation
include( get_template_directory().\'/your-template-name-here.php\' );
exit;
}
}