skip to Main Content

I want to allow visitors who are not logged in to access only specific pages and redirect them to the login page when they access the rest of the pages and posts.

I’ve tried using the following conditional tag, but they don’t work well. It doesn’t allow access to certain pages, but rather blocks them.

if( !function_exists('tf_restrict_access_without_login') ):
 
    add_action( 'template_redirect', 'tf_restrict_access_without_login' );
 
    function tf_restrict_access_without_login(){
         
        /* get current page or post ID */
        $page_id = get_queried_object_id();
 
        /* Pages accessible to non-logged-in users */
        $behind_login_pages = [ 95, 5, 141 ];
 
        if( (empty($behind_login_pages) &&in_array($page_id, $behind_login_pages)) && !is_user_logged_in() ):
        
            wp_redirect( 'https:/example.com/login' );
            return;
            exit;
 
        endif;
    }
 
endif;

I know the cause of this is the if( (empty($behind_login_pages) &&in_array($page_id, $behind_login_pages)) && !is_user_logged_in() ):syntax, and i adding or removing !, ==, !== still doesn’t work.

Can someone help me to modify the code? Thanks!

2

Answers


  1. Here’s a more verbose and isolated version of your function (untested):

    add_action( 'template_redirect', static function () {
        // User is logged in, so no redirect: bail.
        if ( is_user_logged_in() ) {
            return;
        }
    
        // List of IDs guests can access.
        $guest_pages = array( 95, 5, 141 );
    
        // If current page is available to guests, no redirect: bail.
        if ( in_array( get_queried_object_id(), $guest_pages ) ) {
            return;
        }
    
        // User is not logged in, and not a guest page:
        // perform the redirect to login page.
        nocache_headers();
        wp_redirect( wp_login_url() );
        exit;
    } );
    
    Login or Signup to reply.
  2. Try this

    function redirect_non_logged_in_users() {
      $excluded_page_ids = array(95, 5, 141);
    
      if ( ! is_user_logged_in() && ! is_page( 'login' ) && ! in_array( get_queried_object_id(), $excluded_page_ids ) ) {
        wp_redirect( 'https://example.com/login' );
        exit;
      }
    }
    add_action( 'template_redirect', 'redirect_non_logged_in_users' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search