How to have when logged in users click link they get sent to one page, and when logged out users click link they get sent to a different page?

StackOverflow https://stackoverflow.com/questions/19744187

Question

On my Wordpress website I have a page that I only want logged in users to access (e.g. "www.domain.com/logged-in-user-page") and a page that I only want logged out users to access ("www.domain.com/logged-out-user-page"). How can I have it so that if a logged in user types in the domain for the logged out page, they are directed to the logged in page and vice versa. Or clicks on a link and is taken to the correct page whether they are logged in or out.

I've already managed to show and hide the correct page in my navbar menu, but also need to have the redirect when they click on a link I have on my homepage or type in the wrong domain in the address bar. I have seen examples of php script but just can't figure it out. Your help would be greatly appreciated.

Ryan

Was it helpful?

Solution

if(is_user_logged_in()) {
  // Redirect to another page
  header("Location: http://www.example.com/logged-in-page");
} else {
  // Display something else
  header("Location: http://www.example.com/logged-out-page");
}
exit;

For security purposes, you have to add checks to both pages, too, or at least to the logged-in-page:

if(!is_user_logged_in()) {
  header("Location: http://www.example.com/logged-out-page");
  exit;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top