PHP Registering REST Images in WordPress with PHP

Learn how to register and retrieve REST images in WordPress using PHP code. This tutorial explains how to add a custom field to the REST API response for posts, which retrieves the URL of the featured image.

add_action('rest_api_init', 'register_rest_images');

function register_rest_images() {
    register_rest_field(array('post'),
        'fimg_url',
        array(
            'get_callback' => 'get_rest_featured_image',
            'update_callback' => null,
            'schema' => null,
        )
    );
}

function get_rest_featured_image($object, $field_name, $request) {
    if ($object['featured_media']) {
        $img = wp_get_attachment_image_src($object['featured_media'], 'thumbnail');
        if (empty($img)) {
            return false;
        }
        return $img[0];
    }
    return false;
}