-
-
Save bhubbard/297fbd6281bd16a213ca7d7df23d13a4 to your computer and use it in GitHub Desktop.
WordPress API login
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Register login route | |
//Test in postman with - www.yourdomain.com/wp-json/login-user/v1/user | |
function uab_register_endpoints() | |
{ | |
register_rest_route('login-user/v1', '/user/', array( | |
'methods' => 'POST', | |
'callback' => 'uab_login_user' | |
)); | |
} | |
add_action('rest_api_init', 'uab_register_endpoints'); | |
//Callback function for handling login. | |
function uab_login_user(WP_REST_Request $request) | |
{ | |
$username = sanitize_text_field( trim( $request['username'] ) ); | |
$password = trim( $request['password'] ); | |
$remember = $request['remember']; | |
$creds = array( | |
'user_login' => $username, | |
'user_password' => $password, | |
'remember' => $remember | |
); | |
//If wp_signon fails it will return an error. | |
$user = wp_signon( $creds, false ); | |
if ( is_wp_error( $user ) ) | |
{ | |
$error = "Invalid username and password combination"; | |
return new WP_Error( 'login_error', $error, array( 'status' => 422 ) ); | |
} | |
return "Welcome back $username!"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment