Author Name and Avatar in REST API Posts
Adds an author_details field with the author's display name, profile link and avatar URL to every post in the REST API, saving apps a second request or a heavy _embed call.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_field( 'post', 'author_details', array(
'get_callback' => function ( $object ) {
$author_id = (int) get_post_field( 'post_author', $object['id'] );
if ( ! $author_id ) {
return null;
}
return array(
'id' => $author_id,
'name' => get_the_author_meta( 'display_name', $author_id ),
'url' => get_author_posts_url( $author_id ),
'avatar' => get_avatar_url( $author_id, array( 'size' => 96 ) ),
);
},
'schema' => array(
'type' => array( 'object', 'null' ),
'context' => array( 'view', 'embed' ),
'readonly' => true,
),
) );
} );
Notes
Only public profile data is exposed; the author's email and login are never included.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.