How to Automatically Log in Users After Registration

Overview

Would you like to automatically log in users once they’ve registered to your site through the User Registration addon? This will save your new users a step when navigating through your WordPress site. We’ll show you how to use PHP to automatically log in your users after the registration form is submitted.

With the WPForms User Registration addon, you have the option to automatically register a user when the registration form is submitted (no approval required). However, they would still need to fill out a separate login form if they want to log in to the site.

Setup

To set up your registration form to allow for this automatic login, please follow the steps below.

1) Setting up the form settings

First, there are a couple of things to note when setting up your registration form.

  1. Go to Settings » User Registration and make sure theĀ Enable user activation is not be checked.
  2. For the best user experience, set the form confirmation to redirect the user to a new page. Redirecting them to a Thank You page, for example, will clearly show they are logged in. To automatically log in users, make sure you've the Enable user activation is not checked

2) Adding the PHP

Next, add the code snippet below to your site.

/**
 * Automatically log in user after registration form is submitted.
 *
 * @link https://wpforms.com/developers/automatically-log-in-users-after-registration/
 *
 */
function wpf_dev_autologin( $user_id, $fields, $form_data, $userdata ) {

    if ( empty( $userdata['user_login'] ) || empty( $userdata['user_pass'] ) ) {
        return;
    }

    wp_signon( 
        array(
            'user_login'    => $userdata['user_login'],
            'user_password' => $userdata['user_pass'],
            'remember'      => false,
        )
    );
}
add_action( 'wpforms_user_registered', 'wpf_dev_autologin', 10, 4 );

And that’s it! After completing the registration form, your users will not automatically be logged in. Would you like to customize the email that is sent out during the registration process? Take a look at the article How to Change User Email for User Registration Addon.

Action Reference: wpforms_user_registered