Add Featured Image URL to Posts REST Response
Registers a featured_image_url field on the post REST object so headless themes can access the full-size image URL without an extra request.
PHPby SnipCraft
php
<?php
if ( ! function_exists( 'scseed_register_featured_image_url_field' ) ) {
function scseed_register_featured_image_url_field() {
register_rest_field(
'post',
'featured_image_url',
array(
'get_callback' => 'scseed_get_featured_image_url',
'schema' => array(
'description' => __( 'Full URL of the featured image, or null.', 'scseed' ),
'type' => array( 'string', 'null' ),
'context' => array( 'view', 'embed' ),
'readonly' => true,
),
)
);
}
add_action( 'rest_api_init', 'scseed_register_featured_image_url_field' );
}
if ( ! function_exists( 'scseed_get_featured_image_url' ) ) {
function scseed_get_featured_image_url( $object ) {
$thumbnail_id = get_post_thumbnail_id( $object['id'] );
if ( ! $thumbnail_id ) {
return null;
}
$src = wp_get_attachment_image_src( $thumbnail_id, 'full' );
return $src ? esc_url_raw( $src[0] ) : null;
}
}#headless#images#posts#rest-api