How to Automatically Redirect If User Is Already Logged In

Are you interested in implementing automatic redirection for users who are already logged in when they access your login form? Currently, when the login form is displayed on your website, it doesn’t verify if the user is already logged in.

In the User Registration settings, you can hide a login form if a user is already logged in, you can even display a message if they are already logged in. For more information on this feature, please checkout this useful documentation.

But for the purpose of this documentation, we want to automatically redirect a user to a specific page once they are logged in. And in this tutorial, we’re going to walk you through each step.

Creating the form

To begin, you’ll need to create a login form and add it to a WordPress page.

If you need any assistance in how to create a login form with the WPForms User Registration addon, please check out this documentation.

create a login form with WPForms and add it to a WordPress page

Automatically redirect

Now it’s time to copy and paste this snippet to your site.

If you’re not sure how or where to add snippets to your site, please take a look at this tutorial.

/**
 * Automatic redirect from login form if a user is already logged in
 *
 * @link https://wpforms.com/developers/how-to-automatically-redirect-if-user-is-already-logged-in/
 */

function redirect_to_specific_page() {
	
	// enter the page ID of the page that contains the login form
    $page_id = 345; // Change page ID
	
	// if the user is on the login form page and the user is logged in then redirect
    if ( is_page($page_id) && is_user_logged_in() && ! current_user_can('edit_post', $post_id) ) {
		
		// enter the URL of the page you would like to redirect them to
        wp_redirect( 'http://www.example-site.com/your-page/', 301 ); 
		
        exit;
    }
}
add_action( 'template_redirect', 'redirect_to_specific_page' );

There are a few variables in the snippet above you’ll need to change. First, you need to change $page_id = 345 from 345 to match the page ID that your login form is on. If you need to find the page ID number, just edit the page your WPForms login form is on, and in the URL, look for the number that is listed after the ?.

look for the number in the URL when editing the page to find the page ID number

Next, you’ll need to update the URL that is shown inside the wp_redirect action to redirect the user to another page if they are logged in.

And that’s it! Would you like to have your form redirected to a new browser window? Check out our tutorial on How to Open Redirect in a New Window.

Reference Action

template_redirect