How to automatically log in a user after registration in WordPress

To automatically log in a user after registration in WordPress, you can use the user_register action hook.

The following code snippet demonstrates how to do this:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function my_theme_auto_login_after_registration($user_id) {
    // Log in the user
    wp_set_current_user($user_id);
    wp_set_auth_cookie($user_id);

    // Redirect the user to a specific page (e.g., their account page)
    // Change the URL to the desired destination after login
    $redirect_url = home_url('/account/');
    wp_safe_redirect($redirect_url);
    exit;
}
add_action('user_register', 'my_theme_auto_login_after_registration');

This code snippet creates a function called my_theme_auto_login_after_registration() that takes the user ID as a parameter. The function logs in the user using wp_set_current_user() and wp_set_auth_cookie() functions and then redirects them to a specific page (e.g., /account/) using wp_safe_redirect().

  1. Click “Update File” to save the changes.

Now, when a user registers on your site, they will be automatically logged in and redirected to the specified page.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Note: This code snippet assumes that you are using the default WordPress registration process. If you are using a custom registration form or a plugin that handles registration, you may need to modify the code or hook into a different action to achieve the desired behavior.

Leave a Reply

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