form – auto-login on user registration

Sometimes the user have a smoother experience if it is possible to login automatically after registration. For example, I’ve used this functionality on a directory website where registered users can publish their own business.

On the add business page, if the user is logged in, I display my “add new business” Toolset Form, if the user is not logged in, I display the login form and a Toolset User Form to register new users.

Instead of reload the login form after register, I can reload the page, then auto-login the user and display the my “add new business” Toolset Form.

I can do this with this function called by a cred_submit_complete action:


/**
 * Auto log-in new user
 */
add_action( 'cred_submit_complete', 'tssupp_cred_autologin', 10, 2 );
function tssupp_cred_autologin( $post_id, $form_data ){

  if ( $form_data['id'] == 55 ) { // Edit as required

    if ( !empty( $_POST['user_email'] ) ) {

      $user = get_user_by( "email", $_POST['user_email'] );

      // Redirect URL //
      if ( !is_wp_error( $user ) ) {
        wp_clear_auth_cookie();
        wp_set_current_user ( $user->ID );
        wp_set_auth_cookie  ( $user->ID );

        $redirect_to = get_site_url().'/denunciar/';
        wp_safe_redirect( $redirect_to );
        exit();
      }

    }
  }
}


This funtion works also in the case of a form with autogenerate user name, password and alias:
auto-generate-password

The form could display only a field for email and it can send user login and password by a form notification:

notifications-credentials

get_user_by() reference: https://developer.wordpress.org/reference/functions/get_user_by/
wp_safe_redirect() reference: https://developer.wordpress.org/reference/functions/wp_safe_redirect/

Remember to change “$form_data[‘id’] == 55” with your Toolset User Form ID.

You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/autologin-after-registration-with-autogenarate-password/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>