Attach featured image to custom endpoints

To attach anything onto the results, you need to loop through each item and set the property on the object before you return it. You can do a for loop or an array_map() which essentially does a loop and sets the value for each item in the return array to what is returned by the external function.

Here is a simple way to get the featured image from the post and set it on the item. If you need more information on the object when returned then follow the pattern below.

You would put this just after you called get_posts() and before you set the return data.

// query the posts

$posts = get_posts($args);

// create a map function

$add_featured_image = function( $post ) 
{
    // get the featured image id

    $image_id = get_post_thumbnail_id( $post );

    // add the url to the post object

    $post->thumbnail = wp_get_attachment_url( $image_id, 'full' );

    // return the modified value

    return $post;
};

// run the posts through the map

$posts = array_map( $add_featured_image, $posts );

Now your posts will contain a link to the full featured image.

Leave a Comment