I’m encoding in JSON a bunch of data from a WP Query:

$args = array(
    'posts_per_page' => 20,
    'post_type' => 'post',
    'category' => 6,
    'meta_key' => 'custom_total_hits',
    'tag' => 'indie-pop',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-40 days')) 

$query = new WP_Query( $args ); 
$posts = $query->get_posts();   

foreach( $posts as $post ) {    
    $output[] = array( 
    'id' => $post->ID, 
    'title' => $post->post_title, 
    'count' => $post->custom_total_hits, 
    'soundcloud_url' => $post->soundcloud_song, 
    'soundcloud_id' => $post->soundcloud_ids, 
    'link' => get_permalink($post), 


echo json_encode($output);

I would like to display in my JSON a key corrisponding to the src of the medium size of the attached image. If I use 'images' => get_attached_media('image', $post->ID) it retrives an array of multiple data which I can not access since I don’t know the ID of the attached image when I process the data of my JSON. How can I do to retrieve a first level key – value where the value is the src of the attached image?

Read more here: WP query retrieve the src of the attached image


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: