Hello.
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 Conditional Tags in WordPress, but it doesn’t work very well.
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;
Can someone help me modify the following code? Thanks!
[ad_2]
That code looks OK. What bugs or errors are you getting when you use and test it?
Remove the `return;` though.