0

I'm making a query to encode in JSON a bunch of wordpress post data in this way:

$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);
}
echo json_encode($output);

But how can I add to my JSON also the permalink of the $post->ID and the url of the attached image? In order to have something like:

{
"id":28197,
"title":"Hazel English - More Like You",
"count":"000000421",
"soundcloud_url":"https:\/\/soundcloud.com\/hazelenglish\/hazel-english-more-like-you-2",
"soundcloud_id":"317317206",
"link":" ",
"image_url":" "
}

1 Answer 1

3

Look here: Permalink and Attached media

$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), 
'images' => get_attached_media('image', $post->ID) );
 } 
echo json_encode($output);

As you can see in documentation, function get_attached_media return an array with all data of type selected from indicated post.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, what if I would like to return only the url of the attached image? cause I'm not able to access to the url via json since the key is the ID (which is unknown) of the attached media

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.