WordPress : Redirect when user is logged in & on login page

I’m tring to redirect my logged users supposing that they will somehow end up on the login page (Redirection to the member area).

Here is my code, located in my functions.php file :

Read More
if ( is_user_logged_in() && is_page(ID) ) {
    wp_redirect('mydomain.com/my-member-area/');
    exit;
}

So, I tried putting the page ID, or the slug between ”, but it won’t work.

And when I remove the && is_page(ID) part, redirection works on every single page (logically).

Related posts

Leave a Reply

5 comments

  1. All answer here did not work for me, This worked for me:

    function add_login_check()
    {
        if (is_user_logged_in()) {
            if (is_page(6005)){
                wp_redirect('mydomain.com/my-member-area/');
                exit; 
            }
        }
    }
    
    add_action('wp', 'add_login_check');
    
  2. Problem solved, thanks to Manishie !

    My function wasn’t hooked, my bad ! I wasn’t seeing this obviously !

    So here is my working code now :

    function add_login_check()
    {
        if ( is_user_logged_in() && is_page(6005) ) {
            wp_redirect('mydomain.com/my-member-area/');
            exit;
        }
    }
    
    add_action('wp', 'add_login_check');
    

    You made my day ! Thank you Manishie.

  3. function add_login_check()
    {
        if ( is_user_logged_in() && is_page(6005) ) {
            wp_redirect('mydomain.com/my-member-area/');
            exit;
        }
    }
    add_action('wp', 'add_login_check');
    
  4. Thing is, using a page ID through the is_page statement is an hacky way, not suitable for production.

    Additionally using the wp action will be called on every page as it fires once the WordPress environment has been set up… A much better approach would be to use login_init which only fires when the login form is initialized.

    This is based on the assumption that you are still using the default WordPress login system. If a user is already logged in and visit a wp-login.php page, the redirect will fire and push him to the profile page.

    We also need to ignore the logout url as it will prevent the user from disconnecting, we will be using str_contains to ignore any url containing wp-login.php?action=logout.

    /**
     * Redirect to the profile page if the user is already logged in
     * 
     * @param NULL
     * @return NULL
     */
    add_action( 'login_init', 'redirect_to_the_profile_page_if_the_user_is_already_logged_in' );
    
    function redirect_to_the_profile_page_if_the_user_is_already_logged_in() {
    
        if ( is_user_logged_in() && ! str_contains( basename( $_SERVER['REQUEST_URI'] ), 'wp-login.php?action=logout' ) ) {
    
            $user_id = get_current_user_id();
    
            $location = get_author_posts_url( $user_id );
           
            wp_safe_redirect( $location );
    
            exit;
    
        };
    
    };