Redirect if user goes to certain page and not logged in

I’m using the code below, which seems to look fine to me, but when I use it it is having re-direct problems, so its either a conflict somewhere or I have the code wrong.

So what I need, is if the user isn’t logged in but tries to access any of the pages below, they get re-directed away

add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if (is_page( array('sim-racing','support-forum','live-timings-screen','race-rules','race-calendar','events-sim','sim-racing-downloads','cars')) && !is_user_logged_in() ) {
wp_redirect( 'http://www.mywebsite.com/support-forum/', 301 ); 
  exit;
    }
}

Or is this a better way to put it

add_action( 'template_redirect', function() {
  if ( is_user_logged_in() || ! is_page() ) return;
  $restricted = array('sim-racing','support-forum','live-timings-screen','race-rules','race-calendar','events-sim','sim-racing-downloads','cars'); // all your restricted pages
  if ( in_array( get_queried_object_id(), $restricted ) ) {
    wp_redirect( site_url( '/user-registration' ) ); 
    exit();
  }
});

Try this:

add_action( 'template_redirect', function() {

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

  $restricted = array( 'sim-racing', 'support-forum' ); // all restricted pages

  if ( in_array( get_queried_object_id(), $restricted ) ) {
    wp_redirect( 'http://www.mywebsite.com/support-forum/', 301 ); 
    exit();
  }
});
1 Like

Cheers Archie22is,

I’ll log into it tonight and let you know.

Fingers crossed

Sorry its takln a long time to get back on this, but I tried the code above and it didnt work.

Even though I was logged out I can still access the page via the url, which shouldnt be allowed until they log in.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.