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
Here’s a more verbose and isolated version of your function (untested):
Try this