REST API & Developer PHP Beginner

Add the Featured Image URL to the REST API

Add a featured_image_url field to posts in the REST API, so apps and headless front ends don't need a second request for the image.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
add_action( 'rest_api_init', function (): void {
	register_rest_field( 'post', 'featured_image_url', [
		'get_callback' => function ( array $post ): ?string {
			$url = get_the_post_thumbnail_url( $post['id'], 'large' );
			return $url ?: null;
		},
		'schema'       => [
			'description' => 'URL of the featured image, Large size.',
			'type'        => [ 'string', 'null' ],
			'format'      => 'uri',
			'context'     => [ 'view', 'edit', 'embed' ],
			'readonly'    => true,
		],
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

The REST API only gives a post’s featured image as an ID. To show it, an app has to make another request to the media endpoint, or use ?_embed, which returns far more data than needed. This snippet adds the image URL directly.

How it works

register_rest_field() adds an extra field to an object type’s REST responses. The get_callback runs for each post and returns the Large image URL, or null when there’s no featured image.

The schema describes the field, so it shows up correctly in OPTIONS requests and in the REST API’s own documentation, and marks it read-only.

Things to watch

  • Change 'post' to [ 'post', 'page' ] or your post type to add it elsewhere.
  • Use the _fields parameter to keep responses small, for example ?_fields=id,title,featured_image_url.

How to test it

Visit /wp-json/wp/v2/posts. Each post should include featured_image_url.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only