I went through this article and create a custom endpoint so that I can specify multiple meta key and value pairs for filtering. However I have no clue to attach featured image on this result. How can I achieve this?
1 Answer
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.
-
1Thanks. i noticed that the response structure is different between default api end point and customized one. default one comes with structure(post.title.rendered etc.) and customized one is just flat one post_title,post_date..etc) Should be the same? Commented Mar 19, 2016 at 1:04
-
-
I'm trying to figure out what methods end up creating the default REST API structure for a post object. Besides
post.title.rendered
(alsocontent.rendered
andguid.rendered
the default JSON response also includes a nicely populated_links
object and several other properties. Commented Jan 23, 2017 at 20:04 -
@joemaller - I've wondered the same. You might want to ask in the Slack Channel.– jgraupCommented Jan 23, 2017 at 23:13
-
2@jgraup I think I got something, I'll try to confirm this on Slack when I get a chance. wordpress.stackexchange.com/questions/253702/… (also, hi! I knew your name/avatar was familiar) Commented Jan 24, 2017 at 3:55