How can I pass get_the_author_meta(‘user_email’) through the REST API?

Why I Don’t Have Access to Post’s Information?

When you are using Admin-AJAX or the REST API, you will only have access to the current user’s data (by that I mean by default, such as using is_user_logged_in()). To retrieve any other information, you have to pass it as an argument in your AJAX request. WordPress will not load the whole stuff in an AJAX request, so you have to find a workaround.

Using Hidden Inputs:

Since you don’t have access to any post-related information (such as the post’s ID), and approach would be to include a hidden input and add the extra data to it:

<input id="my-hidden-input" type="hidden" value="User ID Here" />

This goes anywhere in your page.php file. Now you can fetch it by using this simple jQuery command:

var userId = $('#my-hidden-input').val();

Localizing the Script:

There is a better alternative to do this, and it’s by using wp_localize_script(). Let’s say you are enqueuing your main JS file as follows:

wp_enqueue_script('my-js-handle','some/path/here.js');

You can pass the necessary data to your JS file, by localizing it. For example, we need to pass the post’s ID. We can do so by creating a conditional and localizing our script:

if( is_page() ){
    $localization_array(
        'post_id' => get_the_ID(),
    );
    wp_localize_script( 'my-js-handle', 'my_object_name', $localization_array, )'
}

Now we can access the post’s ID in our script as simple as this:

window.alert( my_object_name.post_id );

Some Notes:

  • You should have an enqueued JS file to use the second method
  • The handle name of the localized script must be the same as enqueued script
  • You should localize your script “before” you enqueue it