• Resolved Salih K

    (@salihkulangara)


    I have used a function to register rest field as below:

    add_action('rest_api_init', 'register_rest_images' );
    function register_rest_images(){
        register_rest_field( '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' );
            return $img[0];
        } else {
    		return false;
    	}
    
    }

    when I check this- https://mysite.local/wp-json/wp/v2/posts
    it returns fimg_url with the image url, but when I try this –
    https://mysite.local/wp-json/wp/v2/posts?_fields=fimg_url
    it always returs false

    Am I using this in a wrong way? I have used some other fields other that using featured image, that works. So any advices will be helpful.

Viewing 1 replies (of 1 total)
  • Thread Starter Salih K

    (@salihkulangara)

    Ooops!
    My bad, I was trying to get the featured image by Post Id using wrong function,
    I should have got the image id using get_post_thumbnail_id($object[‘id’]); then using wp_get_attachment_image_src().

Viewing 1 replies (of 1 total)
  • The topic ‘WP REST API: _fields not returning featured image’ is closed to new replies.