Need advice on how to use Conditional Tags.

[ad_1]

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]
1 Comment
  1. That code looks OK. What bugs or errors are you getting when you use and test it?

    Remove the `return;` though.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer