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

    get_header();

    if(is_user_logged_in()){
        // content for login user
    } 
    else {
        // https://developer.wordpress.org/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;
    }
?>

3 Answers 3

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.

1
  • I am debug my code and found warning like "header already sent". your suggestion is good but it was not worked. Thanks for your answer. Commented Sep 22, 2017 at 5:00
0

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"

0

try this code,

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

if(is_user_logged_in()){
    // content for login user
} 
else {
$url = 'http://example.com';
wp_redirect($url);
    exit();
} 
2
  • 1
    Please explain how this solves the problem.
    – Milo
    Commented Sep 21, 2017 at 12:56
  • Thanks for your responce but i am alredy try this thing in my template code, It's not working.. Commented Sep 22, 2017 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.