当设置了特定的GET参数时,如何能够加载不同的模板文件?
我想创建一个帐户详细信息页面。所以当account
参数已设置,例如应加载account.php
而不是index.php
.
URL如下所示:example.com?account=user_name
当设置了特定的GET参数时,如何能够加载不同的模板文件?
我想创建一个帐户详细信息页面。所以当account
参数已设置,例如应加载account.php
而不是index.php
.
URL如下所示:example.com?account=user_name
刚刚找到了一个非常简单的解决方案:
add_action( \'template_include\', \'account_page_template\' );
function account_page_template( $template ) {
if( isset( $_GET[ \'account\' ] ) ) {
return locate_template( array( \'account.php\' ) );
}
return $template;
}
但是,对于这类事情,使用某种permalink结构似乎很自然,因此,这里是我的最终代码的一部分,它使URL结构像example.com/account/user_name
可能的:// Register to query vars
add_filter( \'query_vars\', \'add_query_vars\');
function add_query_vars( $vars ) {
$vars[] = \'account\';
return $vars;
}
// Add rewrite endpoint
add_action( \'init\', \'account_page_endpoint\' );
function account_page_endpoint() {
add_rewrite_endpoint( \'account\', EP_ROOT );
}
// Load template
add_action( \'template_include\', \'account_page_template\' );
function account_page_template( $template ) {
if( get_query_var( \'account\', false ) !== false ) {
return locate_template( array( \'account.php\' ) );
}
return $template;
}
在acccount.php
模板您可以如下方式获取参数值:$user_name = get_query_var( \'account\', false );
我有Wp博客,需要在分类页面上接收一个自定义参数,以过滤像我的规则这样的帖子。例如:http://mysite.com/category/teste?myvar=ABC如何从URL获取myvar?我在网上尝试了很多例子,但没有一个适合分类页面。谢谢