<?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
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
.
-
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
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.com';
wp_redirect($url);
exit();
}
-
1
-
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