1

我正在尝试检测用户的页面,然后基于此重定向,现在只是为了测试目的,因为我想验证用户角色,如果他们是某个角色,他们将从页面重定向出去。无论如何,尽管进行了研究和反复试验,以下代码仍无法正常工作:

function wpse12535_redirect_sample() {

    if(is_page_template('list-projects.php')) {
        wp_redirect('http://url.com.au/profile');
    }

}

add_action( 'init', 'wpse12535_redirect_sample' );
4

2 回答 2

2

在 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() 不会自动退出,并且应该几乎总是在调用 exit 之后;:

编辑:Raunak 的回答是正确的,您需要将您的钩子从 init 更改为 wp 或 template_redirect 操作:

https://codex.wordpress.org/Plugin_API/Action_Reference

于 2017-03-23T01:42:19.173 回答
2

笔记

  1. 您应该在;之后添加exit()die()wp_redirect()
  2. wp改为在init. 这将确保您已经加载了模板。
  3. 如果模板文件在子目录下,那么您必须检查该部分。例如: /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 文件中。
代码经过测试并且可以工作。

希望这可以帮助!

于 2017-03-23T07:28:12.260 回答