0

I'm trying to add some user meta information to the existing wp/v2/users REST endpoint. However, it looks like additional authentication is required, i.e. I get this (output in comments):

    error_log( is_user_logged_in() ); // true
    register_rest_field( 'user',
        'is_logged_in',
        array(
            'get_callback' => function () {
                return is_user_logged_in(); // false
            },
        )
    );

(so it doesn't seem possible to get actual user meta in the new field I registered).

Firstly: please correct me if I'm wrong on this point because it would make things much easier.

However, assuming additional authentication is required: I tried just setting _wpnonce to the nonce I got when logged in, and got back a 403. I simply want to be able to send any user who is logged in their own user data in JSON format. What is the correct way to do this?

  • You should read the documentation about authentication with the REST API. – swissspidy Feb 11 '18 at 17:40
  • I did, hence the question (see last paragraph). I need to be able to output this info without additional HTTP headers that aren't in GET, and when trying to set GET _wpnonce it didn't work—I probably didn't get the right nonce. This is where my understanding seems to end. – Ynhockey Feb 12 '18 at 7:14
  • The documentation shows you how to get the proper nonce. You can enqueue the 'wp-api' script and the nonce will be available via wpApiSettings.nonce. If you want to do it on your own, use wp_create_nonce( 'wp_rest' ) to create the nonce. – swissspidy Feb 12 '18 at 7:19
0

It is a bad API design to return different structure based on "external data" not passed in the request itself.

Either construct different API for logged in users and use a different end point for it, or return a "filler" when the user do not have permission to access the data.

(and it is always a bad idea to make modifications to the official rest API as you might create incompatibilities with other users of it, so at least be careful use prefixes etc)

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.