admin管理员组

文章数量:1429013

<?php  
    /** 
     * Template Name: Custom Page Template
     */  

    get_header();

    if(is_user_logged_in()){
        // content for login user
    } 
    else {
        // /
        // wp_redirect() does not validate that the $location is a reference to the current host
        // That means this function is vulnerable to open redirects if you pass it a $location supplied by the user. 
        // So use it only when navigating to another website
        wp_safe_redirect('/wp-login.php');
        exit;
    }
?>
<?php  
    /** 
     * Template Name: Custom Page Template
     */  

    get_header();

    if(is_user_logged_in()){
        // content for login user
    } 
    else {
        // https://developer.wordpress/reference/functions/wp_redirect/
        // wp_redirect() does not validate that the $location is a reference to the current host
        // That means this function is vulnerable to open redirects if you pass it a $location supplied by the user. 
        // So use it only when navigating to another website
        wp_safe_redirect('/wp-login.php');
        exit;
    }
?>
Share Improve this question edited May 24, 2019 at 9:53 SnnSnn 1335 bronze badges asked Sep 21, 2017 at 9:56 Rajnish SuvagiyaRajnish Suvagiya 351 silver badge8 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 5

Redirects are performed by outputting HTTP headers, wp_redirect() just adds some bits on top of it for flexibility.

Headers are only ever meant to be used before any and all output to a page, since that is how HTTP response is structured.

Hypothetically it could work in template if you make sure it fires before any output. Practically it is a normal practice to deal with redirects on an appropriate hook, before any template/output is ever reached. The common hook to use is template_redirect.

As I know you can use wp_redirect before content is sent to the browser. You should use hooks for that.

But you can use PHP header function

if ( TRUE ) {
header( "Location: " . home_url() );
die();
}

But I am not 100% sure is this header(Location) gonna make you problem with "headers already sent"

try this code,

get_header();
global $current_user;
get_currentuserinfo();

if(is_user_logged_in()){
    // content for login user
} 
else {
$url = 'http://example';
wp_redirect($url);
    exit();
} 

本文标签: wp redirectwpredirect() does not work in custom template file