Redirect the specific page to login page if user not logged in before

I want to redirect the homepage to login page for guest users without plugin.

2 Answers
Kaviya Manoharan
Kaviya Manoharan

You can get the output by updating the below codes on function.php

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {
    if ( is_page('slug') && ! is_user_logged_in() ) {
        wp_redirect( 'http://www.example.com/', 301 );
        exit;
    }
}

Also you can use the page_id or page_title instated of slug on the above code. 

// When Page ID is 10 being displayed.
is_page( 10 );
// When the Page with a page_title of "Profile" is being displayed.
is_page( 'Profile' );
// When the Page with a page_name (slug) of "profile" is being displayed.
is_page( 'profile' );
Archana
Archana

You can redirect the page using following script codes on that specific page, if you have class name (logged-in) in the body tag. Many themes supports to add class name on body tag if they logged in.

if (document.body.classList.contains('logged-in')) {
 alert("Already Logged In");
} else {
 location.assign("http://www.example.com/");
}

 

Archana
Kaviya Manoharan

If your theme not having this class name functionality then just check the link and follow the codes to add class name in body tag based on the user login.

Thanks.

4 likes
Add Your Answer