Question

How can I get the email adress from the users by using the REST API? I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info?

This is my JS:

(function($) {

    var nonce       = WPsettings.nonce;
    var rest_url    = WPsettings.rest_url;

    $.ajax( {
        url: rest_url + 'users/',
        dataType: "json",
        beforeSend: function ( xhr ) {
            xhr.setRequestHeader( 'X-WP-Nonce', nonce );
        }
    } )
   .done( function ( response ) {
        console.log( response );
    } );

})(jQuery);
Was it helpful?

Solution

you should adding email field in your output.

Use the below hook in your functions.php in your current theme:

register_rest_field( 'user', 'user_email',
    array(
        'get_callback'    => function ( $user ) {
            return $user['email'];
        },
        'update_callback' => null,
        'schema'          => null,
    )
);

But, it not recommended! because everyone can see emails.

OTHER TIPS

I think u can return current_user email,

register_rest_field( 'user', 'user_email',
    array(
        'get_callback'    => function ( $user ) {
            return wp_get_current_user()->user_email;
        },
        'update_callback' => null,
        'schema'          => null,
    )
);

If you're having an issue getting the email using Mostafa's answer, I had better luck swapping out the email retrieval as such:

register_rest_field( 'user', 'user_email',
                        array(
                            'get_callback'    => function ( $user ) {
                                return get_userdata($user['id'])->user_email;
                            },
                            'update_callback' => null,
                            'schema'          => null,
                        )
                    );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top