1

I've seen this question posted before but not exactly trying to achieve what I want.

Basically what I want is: If user is not logged in AND is on -this page- OR -this page- OR -this page, redirect him to -this page- (which is a custom registration page)

I'm tweaking this piece of code, but it's not working. I'll appreciate any type of guidance.

<?php
function redirect_non_logged_in(){
  // if user is not logged and is on this pages
  if( !is_user_logged_in() && is_page( array( 250, 253 ) ) { 
    //This redirects to the custom login page.
    wp_redirect(site_url('/user-registration'));
    exit();
  }
}
add_filter('get_header','redirect_non_logged_in');
?>
0

2 Answers 2

6

Your function is fine, but 'get_header' it's too late.

Use template_redirect instead:

add_action( 'template_redirect', function() {

  if ( is_user_logged_in() || ! is_page() ) return;

  $restricted = array( 250, 253 ); // all your restricted pages

  if ( in_array( get_queried_object_id(), $restricted ) ) {
    wp_redirect( site_url( '/user-registration' ) ); 
    exit();
  }

});

Be sure to not include 'user-registration' page id in $restricted array or you'll experience an endless redirect...

3
  • Really appreciate it. This works.
    – rohn
    Mar 20, 2014 at 6:07
  • Sorry to interrupt, but rather than replicating the question, I'd ask you here. I use this slightly alternated code based on your answer: add_action( 'template_redirect', function() { if ( !is_page('login') || !is_user_logged_in() ) { wp_redirect( site_url( '/login', 301 ) ); exit(); }});, however, I still receive the redirecting loop. Can you point out what is wrong? Aug 13, 2014 at 1:52
  • Your problem is that login is not a page, so is_page('login') can't ever be true. To know if you are on login page is not strainforward in WordPress, see this answer to know how to do. @FrederickAndersen
    – gmazzap
    Aug 13, 2014 at 12:51
-3

Install page restrict https://da.wordpress.org/plugins/pagerestrict/

In settings choose login form show no

insert link in restriction message: <a href="https://your login page/">Login</a> to view this page/post

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