Contents [hide]
The users/me endpoint in WordPress
WordPress has a built in endpoint that you can use to query information about the current user. While you are logged in you can send a GET /wp-json/wp/v2/users/me
to query some useful information about the current user.
I skipped over this the first couple of times when studying the WordPress default endpoints. It can be found here: https://developer.wordpress.org/rest-api/reference/users/#definition-example-request-2
Extending the users/me endpoint
You can add information to the endpoint by doing the following.
- you register a field to the endpoint user.
- in your callback you get the desired value.
An example of how to add the user mail
Here is a code snippet that adds the user email address to the response.
12345678910111213141516function email_add_user_data() {register_rest_field( 'user','user_email',array('get_callback' => 'rest_get_user_field_mail','update_callback' => null,'schema' => null,));}add_action( 'rest_api_init', 'email_add_user_data' );function rest_get_user_field_mail( $user, $field_name, $request ) {$current_user = wp_get_current_user();return $current_user->user_email;}
Leave a Reply