Re-Direct ALL Users to the Home Page IF not logged in

I just read the codex on wp_redirect(); and found an example that I modified. Problem is, all I get is an error in my browser saying “The page isn’t redirecting properly”.

I need all users, unless logged in, to be re-directed to the home page (home_url()).

Can someone please help me?

add_action( 'template_redirect', 'not_logged_in_redirect_home' );
add_action( 'do_feed', 'not_logged_in_redirect_home' );
function not_logged_in_redirect_home() {

        if ( is_home() ) return;

        if ( ! is_user_logged_in() && is_home() ) return;

        if ( ! is_user_logged_in() && !is_home() ) {
    
            wp_redirect( home_url() );
    
            exit;
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Perhaps something like this?

add_action( 'template_redirect', 'not_logged_in_redirect_home' );
add_action( 'do_feed', 'not_logged_in_redirect_home' );
function not_logged_in_redirect_home(){

    if ( is_user_logged_in() ){

        return false;

    }

    if ( 
        ! is_home() // use this option if you show blogs posts on the home page
        // ! is_front_page() // use this if you show a static page
    ){

        wp_redirect( home_url() );

        exit;
    }
}

Check the documentation on is_home() – https://developer.wordpress.org/reference/functions/is_home/

Since WordPress 2.1, when the static front page functionality was introduced, the blog posts index and site front page have been treated as two different query contexts, with is_home() applying to the blog posts index, and is_front_page() applying to the site front page

So, you might need to use is_front_page() – depending on your setup.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x