How to block access to blog-page for users not logged in?

My blogpage [is_home()] is located at /blog. My static page [is_frontpage()] is not the blogpage and located to /about-us.

For users not logged in, the startpage is the static page.
For users logged in, the startpage is the blogpage.

So far so good. But I want to restrict not logged-in users from the content of the blogpage. If a user is not logged in, he has always access to the blogpage by using the link www.mypage.com/blog

I tried the following code:

add_action ( 'template_redirect', 'redirect_my_homepage' );
function redirect_my_homepage(){
if ( is_home() && !is_user_logged_in() ) {
        wp_redirect('http://www.mypage.com') ;
        exit();
    }
}

But this prevents users from logging in, as a logged-in user will automatically be redirected to the blogpage -> the code will redirect users back to the static page and prevent the login.

So, I am looking for a piece of code to prevent access to the blog-page for not logged-in users.

1 Answer
1

You can do this way

function block_access() {
  if (is_page (blog) && !is_user_logged_in ()) {
    $loginUrl = home_url('/login-page/');
    wp_redirect($loginUrl);
    exit(); 
  }
}
add_action( 'template_redirect', 'block_access' );

Leave a Comment