Code to redirect logged in users not working properly

I’m trying to redirect all logged in users that try to access the homepage of my site to another page using the following code snippet but, for some reason, they are also redirected if trying to access the Blog page, not sure why. I was following the suggestions of this thread: https://premium.wpmudev.org/forums/topic/home-page-redirection-for-logged-in-users#ref and this is the code that I’m currently using:

  • Adam Czajczyk
    • Support Gorilla

    Hello Joshua

    I hope you’re well today and thank you for your question!

    This seems to be caused by the “is_front_page()” being checked in the code. The “is_front_page()” is a bit “tricky” because it’s a boolean function that returns TRUE or FALSE but it returns TRUE if:

    “he main blog page is being displayed and the Settings->Reading->Your homepage displays is set to “Your latest posts”, or when Settings->Reading->Your homepage displays is set to “A static page” and the “Front Page” value is the current Page being displayed. ” [reference: https://codex.wordpress.org/Function_Reference/is_front_page]

    The “is_home()” function behavior also is slightly different depending on what are the settings of the site.

    In this case, the “is_front_page()” would return true when visitor is viewing an actual homepage and the “is_home()” would return true when the visitor is viewing the blog content page. Since there’s “OR” operator between these two functions in the code, it would cause the redirect to be executed in both these cases.

    That said, try this version instead, please:

    add_action('wp_head','wpmy_redirect_logged_in_users_away_from_home');
    function wpmy_redirect_logged_in_users_away_from_home() {
    global $pagenow;

    if( is_user_logged_in() && $pagenow != 'wp-signup.php' && is_front_page() ) {
    wp_redirect('http://j***m.com/members/activity-stream/');
    exit;
    }
    }

    Let me know, please if it worked for you.

    Best regards,

    Adam

  • Joshua
    • WPMU DEV Initiate

    Perfect! The fix works perfectly. Thank you for taking the time to explain the problem in detail and provide the needed solution. I’m glad someone was finally able to figure out what was causing the issue. It had us scratching our heads. Thanks again!

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.