Register/login user with WordPress JSON API

1.Paste Following code in your themes function.php file.

2.Make sure that WP-REST-API plugin Should be installed on wordpress site

add_action( 'rest_api_init', 'register_api_hooks' );

function register_api_hooks() {
  register_rest_route(
    'custom-plugin', '/login/',
    array(
      'methods'  => 'POST',
      'callback' => 'login',
    )
  );
}

function login($request){
    $creds = array();
    $creds['user_login'] = $request["username"];
    $creds['user_password'] =  $request["password"];
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) )
      echo $user->get_error_message();

    return $user;
}

add_action( 'after_setup_theme', 'custom_login' );

Then your API will be created as

http://www.url.com/wp-json/custom-plugin/login

Try it with Postman You will get 200 as a response and user info

Leave a Comment