How to extend WordPress users/me endpoint with user email

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.

  1. you register a field to the endpoint user.
  2. 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.

function 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

Your email address will not be published. Required fields are marked *

Con Schneider