Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Auto Login After Registration in WordPress with core php

I've been trying for days now to take users who have just registered to my WordPress site and automatically log them in and then redirect them to a URL of my choice.

By default, WordPress sends you a username and a password, then you must log in manually. This is a total pain. How can i overcome this.

I have my own registration page(core php page) which successfully adds users into DB. But the point is, i should avoid users to login again.

Once registration is done, it should automatically redirects to home page or profile page.

I am a newbie to wordpress functionalities. It would be grateful if someone(who have knowledge on core functionality of wordpress) at least suggests a way/solution.

Looking forward.
Thanks

like image 221
smallerik Avatar asked Nov 13 '13 09:11

smallerik


People also ask

What is an automatic login?

Automatic login allows you to specify the user account that will be automatically logged in when Workflow is opened on a specific workstation. You can change the configuration of the default account and enable or disable automatic login.


2 Answers

// Add on function.php for Auto login after register and redirect to a home page. varified this code

function auto_login_new_user( $user_id ) {
    wp_set_current_user($user_id);
    wp_set_auth_cookie($user_id);
    $user = get_user_by( 'id', $user_id );
    do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1]
    wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
    exit;
}
add_action( 'user_register', 'auto_login_new_user' );
like image 148
Ravi Patel Avatar answered Oct 19 '22 23:10

Ravi Patel


Following is based on how WooCommerce creates a new user and logs him in:

$user_pass = esc_attr( $_POST['account_password'] );

$new_user_data = array(
    'user_login' => $_POST['account_username'],
    'user_pass'  => $user_pass,
    'user_email' => $_POST['account_email'],
    'role'       => 'subscriber'
);

$user_id = wp_insert_user( $new_user_data );

// Set the global user object
$current_user = get_user_by( 'id', $user_id );

// set the WP login cookie
$secure_cookie = is_ssl() ? true : false;
wp_set_auth_cookie( $user_id, true, $secure_cookie );

to redirect use wp_safe_redirect, e.g.

wp_safe_redirect( home_url( '/' ) );
exit;
like image 20
diggy Avatar answered Oct 20 '22 01:10

diggy