How to get author meta into post endpoint in api v2 in WordPress


I added a code block that has some example stuff for context on registering custom routes. Hope it helps!
Luckily, there are few ways that you can get author meta after calling the REST API.
function wp_get_author_meta($object, $field_name, $request) {

    $user_data = get_userdata($object['author']); // get user data from author ID.

    $array_data = (array)($user_data->data); // object to array conversion.

    $array_data['first_name'] = get_user_meta($object['author'], 'first_name', true);
    $array_data['last_name']  = get_user_meta($object['author'], 'last_name', true);

    // prevent user enumeration.
    unset($array_data['user_login']);
    unset($array_data['user_pass']);
    unset($array_data['user_activation_key']);

    return array_filter($array_data);

}

function wp_register_author_meta_rest_field() {

    register_rest_field('post', 'author_meta', array(
        'get_callback'    => 'wp_get_author_meta',
        'update_callback' => null,
        'schema'          => null,
    ));

}
add_action('rest_api_init', 'wp_register_author_meta_rest_field');

Leave a comment