How to Get Featured Image Thumbnail URL Using WP REST API

By default, WordPress REST API only returns featured image ID in form of featured_media field. However you can easily resolve this issue by adding a small amount of code to your functions.php file located inside root of your theme directory.

To get featured image URL in JSON response, use the following code.

add_action( 'rest_api_init', 'ccw_insert_thumbnail_url' );
function ccw_insert_thumbnail_url() {
    register_rest_field( 'post',
        'ccw_thumbnail',
        array(
            'get_callback'    => 'ccw_get_thumbnail_url',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

function ccw_get_thumbnail_url($post){
	if(has_post_thumbnail($post['id'])){
		$imgArray = wp_get_attachment_image_src( get_post_thumbnail_id( $post['id'] ), 'full' );
		$imgURL = $imgArray[0];
		return $imgURL;
	}else{
		return false;	
	}
}

The name of the field in the json response will be ccw_thumbnail. You can change second parameter of wp_get_attachment_image_src function to get the URL of image with a different image size.

Read Also : How to Add Active Class to Current Menu Item in WordPress

0 Comments

Leave a Comment.