When we are submitting a form with fields username/email and password.
We have to login if user exist and register as new user if there user does not exist.
Below is the code which will help to fulfill our requirement.
Below is the code which will help to fulfill our requirement.
global $wpdb; $email = $_REQUEST['email']; $password = $_REQUEST['password']; // Function to login- If user exists if( email_exists( $email )) { $user = get_user_by( 'email', $email ); $user_id= $user->ID; if ( $user && wp_check_password( $password, $user->data->user_pass, $user->ID) ){ $secure_cookie = is_ssl(); $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array()); global $auth_secure_cookie; $auth_secure_cookie = $secure_cookie; wp_set_auth_cookie($user_id, true, $secure_cookie); $user_info = get_userdata($user_id); do_action('wp_login', $user_info->user_login, $user_info); $msg= 'You are logged In successfully.'; }else{ $msg= 'Username / Password is wrong. Please try again.'; } exit($msg); }else{ // Function to Register - If user does not exists $username = explode("@", $email); $username = sanitize_text_field( $username[0] ); $email = sanitize_text_field( $_REQUEST['email'] ); $password = $wpdb->escape( sanitize_text_field( $password)); $status = wp_create_user($username,$password,$email); $user_id=$status; update_user_meta( $user_id,'first_name', $username); //update user meta //autologin start $secure_cookie = is_ssl(); $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array()); global $auth_secure_cookie; $auth_secure_cookie = $secure_cookie; wp_set_auth_cookie($user_id, true, $secure_cookie); $user_info = get_userdata($user_id); do_action('wp_login', $user_info->user_login, $user_info); //autologin end exit('User is created successfully.'); }
No comments:
Post a Comment