Featured Image URL in the REST API
Adds a featured_image_url field to posts and pages in REST API responses, so headless front ends do not need a second request.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_field( array( 'post', 'page' ), 'featured_image_url', array(
'get_callback' => function ( $object ) {
$id = isset( $object['featured_media'] ) ? (int) $object['featured_media'] : 0;
return $id ? wp_get_attachment_image_url( $id, 'large' ) : null;
},
'schema' => array(
'description' => 'URL of the featured image in the large size.',
'type' => array( 'string', 'null' ),
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
) );
} );
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.