如何通过WordPress API登录并获取用户详细信息?

时间:2018-08-19 作者:Mohammad Shahnewaz Sarker

我想通过WordPress api登录。我尝试了“/wp-json/wp/v2/users”。但它只返回用户1的详细信息。

我的目标是通过api登录并获取所有概要信息。

3 个回复
SO网友:shiv

1. 安装并激活JWT Authentication for WP REST API plugin, 同时安装WP REST API plugin
2. 现在,您可以从移动应用程序或任何其他来源或通过邮递员运行任何wordpress默认api。例如,从应用程序或邮递员点击此url。https://example.com/wp-json/wp/v2/posts
3. 通过应用程序或邮递员,当您使用有效的详细信息(使用rest api)登录时,您将获得一个令牌。要登录并获取令牌,请通过邮递员或应用程序运行以下urlhttps://example.com/wp-json/jwt-auth/v1/token
4. 通过这种方式,您将获得一个令牌,如图所示postman and jwt authentication
现在使用此令牌登录用户详细信息,例如
5. 在函数中生成函数。php

function checkloggedinuser()
{
$currentuserid_fromjwt = get_current_user_id();
print_r($currentuserid_fromjwt);
exit;
}

 add_action(\'rest_api_init\', function ()
{
  register_rest_route( \'testone\', \'loggedinuser\',array(
  \'methods\' => \'POST\',
  \'callback\' => \'checkloggedinuser\'
  ));
});

6. 现在再次在postman或应用程序中运行此新url以登录用户详细信息。https://example.com/wp-json/testone/loggedinuser(用url替换example.com)enter image description here

SO网友:Maher Aldous

你好,我有一个更快更好的解决方案来获取ID,更像用户的化身。

只需将此添加到您的函数中。php文件:

/*
 * Insert some additional data to the JWT Auth plugin
 */
function jwt_auth_function($data, $user) { 
    $data[\'user_role\'] = $user->roles; 
    $data[\'user_id\'] = $user->ID; 
    $data[\'avatar\']= get_avatar_url($user->ID);
    return $data; 
} 
add_filter( \'jwt_auth_token_before_dispatch\', \'jwt_auth_function\', 10, 2 );
参考号:How to ger ID user via API

我希望这有帮助

SO网友:Mohammad Shahnewaz Sarker

Solved:

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, true );


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

    $id = $user->ID;
    $meta = get_user_meta($id);

    return $meta;
}
结束

相关推荐

为什么PER_PAGE不能处理WP API中的类别?

首先,我搜索了几个问题和文档,但似乎是WordPress的v2 许多老问题不再有效。我想做的是从Postman中的一个类别中获取所有帖子或单个帖子,而不是常见的返回10篇帖子,而无需修改函数中的API。php。tldr我从引用REST API Handbook 并查看schema 我看到了categories 我可以使用以下方法返回10个最新类别:http://foobar.com/wp-json/wp/v2/posts/categories_name=hello 引用arguments 我明白