[英]wp_redirect and is_page_template is not working?
我试图检测用户的页面,然后根据它进行重定向,现在只是测试目的,因为我想验证用户角色,如果他们是某个角色,他们将被重定向到页面。 无论如何,尽管研究和反复试验,以下代码仍无效:
function wpse12535_redirect_sample() {
if(is_page_template('list-projects.php')) {
wp_redirect('http://url.com.au/profile');
}
}
add_action( 'init', 'wpse12535_redirect_sample' );
在wp_redirect的末尾添加一个出口:
function wpse12535_redirect_sample() {
if(is_page_template('list-projects.php')) {
wp_redirect('http://url.com.au/profile');
exit;
}
}
add_action( 'init', 'wpse12535_redirect_sample' );
请参阅https://developer.wordpress.org/reference/functions/wp_redirect/#description
注意:wp_redirect()不会自动退出,并且几乎总是会跟着调用退出;
编辑:Raunak的答案是正确的,您需要将挂钩从init更改为wp或template_redirect操作:
注意
- 你应该在
wp_redirect()
之后添加exit()
或die()
wp_redirect()
;- 在
init
上使用wp
代替。 这将确保您已加载模板。- 如果模板文件在子目录下,那么您必须检查该部分。 例如:
/wp-content/themes/my_active_theme/page-templates/list-projects.php
,那么你必须检查page-templates/list-projects.php
以下是适合您的代码:
function wh_redirect_sample()
{
if (basename(get_page_template()) == 'list-projects.php')
{
wp_redirect('http://url.com.au/profile');
exit(); //always remember to add this after wp_redirect()
}
}
add_action('wp', 'wh_redirect_sample');
function wh_redirect_sample() { //if list-projects.php is under sub directory say /wp-content/themes/my_active_theme/page-templates/list-projects.php if (is_page_template('page-templates/list-projects.php')) { wp_redirect('http://url.com.au/profile'); exit(); } //if list-projects.php is under active theme directory say /wp-content/themes/my_active_theme/list-projects.php if (is_page_template('list-projects.php')) { wp_redirect('http://url.com.au/profile'); exit(); } } add_action('wp', 'wh_redirect_sample');
代码位于活动子主题(或主题)的function.php文件中。 或者也可以在任何插件php文件中。
代码经过测试和运行。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.