最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to retrieve user via rest api using custom meta andor email

programmeradmin1浏览0评论

I've successfully added a custom meta key / value for a user and managed to display it in the rest API however I'm not sure how I can retrieve the user based on this key.

For example

$fields = ['trdr'];
foreach($fields as $field){
    register_rest_field('user', $field, [
        'get_callback' => function($user, $field_name, $request) use ($field){
            return get_user_meta($user['id'], $field_name, true);
        },
        'update_callback' => function($user, $meta_value) use ($field){
            update_user_meta($user['id'], $field, $meta_value);
        },
        'schema' => [
            'type' => 'string',
            'description' => 'the customer trdr in softone',
            'context' => ['view', 'edit']
        ]
    ]);
}

The field is successfully retrieved in the users when retrieving by ID but I'm not sure how I can query for the user using this specific rest field.

I'm using the composer package to simplify the process of talking to the API and for example I can do

return $this->wpClient->getClient()->users()->get(null, ['slug' => $slug]);

To retrieve a single user by his slug. However doing it for the email or the field (trdr in my case) doesn't work. Any ideas what extra steps are needed?

The library's code is really straightforward to create the request so it doesn't seem to be because of the library.

    public function get($id = null, array $params = null)
    {
        $uri = $this->getEndpoint();
        $uri .= (is_null($id)?'': '/' . $id);
        $uri .= (is_null($params)?'': '?' . http_build_query($params));

        $request = new Request('GET', $uri);
        $response = $this->client->send($request);

        if ($response->hasHeader('Content-Type')
            && substr($response->getHeader('Content-Type')[0], 0, 16) === 'application/json') {
            return json_decode($response->getBody()->getContents(), true);
        }

        throw new RuntimeException('Unexpected response');
    }

I've successfully added a custom meta key / value for a user and managed to display it in the rest API however I'm not sure how I can retrieve the user based on this key.

For example

$fields = ['trdr'];
foreach($fields as $field){
    register_rest_field('user', $field, [
        'get_callback' => function($user, $field_name, $request) use ($field){
            return get_user_meta($user['id'], $field_name, true);
        },
        'update_callback' => function($user, $meta_value) use ($field){
            update_user_meta($user['id'], $field, $meta_value);
        },
        'schema' => [
            'type' => 'string',
            'description' => 'the customer trdr in softone',
            'context' => ['view', 'edit']
        ]
    ]);
}

The field is successfully retrieved in the users when retrieving by ID but I'm not sure how I can query for the user using this specific rest field.

I'm using the composer package https://github/varsitynewsnetwork/wordpress-rest-api-client to simplify the process of talking to the API and for example I can do

return $this->wpClient->getClient()->users()->get(null, ['slug' => $slug]);

To retrieve a single user by his slug. However doing it for the email or the field (trdr in my case) doesn't work. Any ideas what extra steps are needed?

The library's code is really straightforward to create the request so it doesn't seem to be because of the library.

    public function get($id = null, array $params = null)
    {
        $uri = $this->getEndpoint();
        $uri .= (is_null($id)?'': '/' . $id);
        $uri .= (is_null($params)?'': '?' . http_build_query($params));

        $request = new Request('GET', $uri);
        $response = $this->client->send($request);

        if ($response->hasHeader('Content-Type')
            && substr($response->getHeader('Content-Type')[0], 0, 16) === 'application/json') {
            return json_decode($response->getBody()->getContents(), true);
        }

        throw new RuntimeException('Unexpected response');
    }
Share Improve this question edited Oct 14, 2020 at 19:29 gabtzi asked Oct 14, 2020 at 18:40 gabtzigabtzi 1011 bronze badge 7
  • Are these authenticated requests? Note that for help using that library you should contact their support, there's a very very high chance that this is a problem specific to that library which would make this question off topic here – Tom J Nowell Commented Oct 14, 2020 at 19:22
  • It doesn't seem to be library specific because it's just a frontend to build the query to use with guzzle. I would do pretty much the same. The requests are authenticated – gabtzi Commented Oct 14, 2020 at 19:30
  • Besides I get the same results with postman. – gabtzi Commented Oct 14, 2020 at 19:31
  • have you tried using the same parameters you would pass to WP_Query? – Tom J Nowell Commented Oct 14, 2020 at 19:32
  • I've tried the same way as with WP_User_Query but it didn't work. Any example of how it would be with WP_Query? – gabtzi Commented Oct 14, 2020 at 19:38
 |  Show 2 more comments

1 Answer 1

Reset to default 0

I managed to solve my issue by taking a look at \WP_REST_Users_Controller::get_items and noticing that there's not an automatic way to filter via meta terms. Instead you need to apply_filters to actually input the args in the array.

So in order to achieve my searching I had to do these things.

  1. in functions.php or a plugin
     foreach ($fields as $field) {
        //register meta field
        register_meta('user', $field, [
            'single' => true,
            'show_in_rest' => true,
            'type' => 'string',
        ]);
    
        //register search function in rest api
        add_filter('rest_user_query', function ($args, $request) use ($field) {
            if (isset($request[$field]) && !empty($request[$field])) {
                $args['meta_query'][] = [
                    'relation' => 'AND',
                    [
                        'key' => $field,
                        'value' => $request[$field],
                        'compare' => '='
                    ]
                ];
    
            }
            return $args;
        }, 10, 2);
    }
  1. In the rest request just add the params
    [
        'trdr' => $trdr
    ]

Email can be searched like this

        [
            'search' => $email,
            'search_columns' => ['user_email']
        ]
发布评论

评论列表(0)

  1. 暂无评论