我已使用functions.php
文件中的以下代码向我的Wordpress安装添加了查询字符串:
function add_query_vars($aVars) {
$aVars[] = "username";
return $aVars;
}
add_filter('query_vars', 'add_query_vars');
function add_rewrite_rules($aRules) {
$aNewRules = array(
'([^/]+)/manage' => 'index.php?pagename=manage&username=$matches[1]',
'([^/]+)/settings' => 'index.php?pagename=settings&username=$matches[1]',
);
$aRules = $aNewRules + $aRules;
return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');
但是,如果username
查询字符串为空,我不想加载页面模板,而是我想重定向到主页。例如:
website.com/myusername/manage
...会加载页面模板
website.com/manage
......会重定向回家。
我可以使用Wordpress'重写引擎还是我应该采取另一种方法?
答案 0 :(得分:2)
好吧,我会使用这段代码:
function redirect_to_homepage( $query ) {
//page manage and settings does NOT exits
if ( $query->is_main_query() && ( $query->query_vars['name'] == 'manage' || $query->query_vars['name'] == 'settings' ) ){
if( ( !array_key_exists( 'username', $query->query_vars ) || ( array_key_exists( 'username', $query->query_vars ) && trim($query->query_vars['username']) == '' ) ) ) {
wp_redirect( get_bloginfo('url') );
exit;
}
}
//page manage and settings does exits
if ( $query->is_main_query() && ( $query->is_page('manage') || $query->is_page('settings') ) ){
if( ( !array_key_exists( 'username', $query->query_vars ) || ( array_key_exists( 'username', $query->query_vars ) && trim($query->query_vars['username']) == '' ) ) ) {
wp_redirect( get_bloginfo('url') );
exit;
}
}
}
add_action( 'parse_query', 'redirect_to_homepage' );