In a wordpress template, I’m doing a quick get_posts() call. I’d like the result to be one array of posts, where each post object in the array contains an array of the post’s attachments, (right now I just need the featured image, later I may need more images). The reason: I won’t be looping through this result set in a traditional template where I could simply do ‘the_post_thumbnail()’ – I’m setting up a quick ajax call, so I need one array with all the data to send back to the client.
Can’t find much in the docs or online. I’ve got a working solution, it just feels very inefficient and i’m sure theres a better way…
Herse what I’m doing now:
$ps = get_posts($args);
// ADD POST THUMBNAIL TO POST OBJECT
foreach ( $ps as $post ) : setup_postdata( $post );
$post->img = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
endforeach;
// OUTPUT UPDATED ARRAY AS JSON
header('Content-Type: application/json');
echo json_encode($ps);
die();
So again, I just want one get_posts() call which returns the post array, with the attachment IDs included in each post object. Is this possible?
Thanks!