Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active January 9, 2020 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save itzikbenh/d9d4bef7103ef210db01543914704313 to your computer and use it in GitHub Desktop.
Save itzikbenh/d9d4bef7103ef210db01543914704313 to your computer and use it in GitHub Desktop.
WordPress API login
<?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