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 https://github.com/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');
    }
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
    Oct 14 '20 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
    Oct 14 '20 at 19:30
  • Besides I get the same results with postman.
    – gabtzi
    Oct 14 '20 at 19:31
  • have you tried using the same parameters you would pass to WP_Query?
    – Tom J Nowell
    Oct 14 '20 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
    Oct 14 '20 at 19:38
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']
        ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.