2017-03-23 38 views
1

我想檢測用戶的頁面,然後重定向基於此,只是測試目的,因爲我想驗證用戶角色,如果他們是某個角色,他們將被重定向到頁面。但無論如何,下面的代碼不能正常工作,儘管研究和反覆試驗:wp_redirect和is_page_template不工作?

function wpse12535_redirect_sample() { 

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

} 

add_action('init', 'wpse12535_redirect_sample'); 

回答

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()不會自動退出,並且應該幾乎總是跟着一個電話退出;:

編輯:勞NAK的答案是正確的,你需要你的鉤子從初始化到WP或template_redirect行動改變:

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

+0

感謝您指出,雖然我仍然有訪問頁面時獲取函數觸發的初始問題。 – Elevant

+1

+1爲你的答案,你錯過了一個重要的點是'init',它是在模板加載之前調用的。 –

1

NOTE

  1. You should add exit() or die() after wp_redirect() ;
  2. Use wp instead on init . This will ensure you the template is already loaded.
  3. If the template file is under subdirectory then you have to check with that part. Ex: /wp-content/themes/my_active_theme/page-templates/list-projects.php , then you have to check 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文件中使用。
代碼已經過測試和工作。

希望這會有所幫助!

+0

是的,這是行不通的,我不知道它是否因爲我運行freelancengine主題。但是, – Elevant

+0

請檢查'_wp_page_template'' metakey'中的值。 –