Create & implement custom login form via Ajax to give user login feature. Here I have developed for this a shortcode so easily put this code in any files (in theme functions.php, plugin's file) and can placed shortcode in any template file, sidebar file, page content, post content, widget.
Here I have used only 'wp_ajax_nopriv_' action hook to accept ajax request because 'wp_ajax_nopriv_' action hook is accept only requests are send via frontend pages (non-logged in users).
# now add a ajax handler to receive ajax request # here need to use only 'wp_ajax_nopriv_' action add_action('wp_ajax_nopriv_pkt_login', 'pkt_login'); function pkt_login() { $response = ['status' => false]; if (empty($_POST['data'])) $response['msg'] = 'Please flll out the form!!'; else { parse_str($_POST['data'], $data); if (! wp_verify_nonce( $data['pkt_form_nonce'], 'pkt_nonce' )) { $response['msg'] = 'Our Site is protected!!'; } else { $user_email = sanitize_email($data['email']); $password = $data['password']; if (! is_email( $user_email ) ) { $response['msg'] = 'Error: The email address isn’t correct. or already registered.'; } elseif (!email_exists( $user_email )) { $response['msg'] = 'Error: The email address is not registered.'; } else { $creds = array( 'user_login' => $user_email, 'user_password' => $password, 'remember' => empty($data['remember']) ? false : true ); $user = wp_signon( $creds, true ); if ( is_wp_error( $user ) ) { $response['msg'] = $user->get_error_message(); } else { $response['status'] = true; $response['redirectTo'] = site_url(); $response['msg'] = 'Login successfully.'; } } } } echo json_encode($response); wp_die(); }# Create a shortcode [login_form] so we can put it wherever we want # and this put functions.php or your desire plugin add_shortcode('login_form', 'pkt_login_form'); function pkt_login_form($attr) { /* define desire key index */ $attr = shortcode_atts( array( ), $attr ); extract($attr); ob_start(); require 'login.php'; $return = ob_get_clean(); return $return; } # here login.php page code
No comments:
Post a Comment