WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I json_encode the output of this function I use to get all attached images of a post?

function get_all_images($postid=0, $size='bigger', $attributes='') {
    if ($postid<1) $postid = get_the_ID();
    if ($images = get_children(array(
        'post_parent' => $postid,
        'post_type' => 'attachment',
        'numberposts' => -1,
        'orderby' => 'menu_order',
        'post_mime_type' => 'image',)))
        foreach($images as $image) {
            $attachment=wp_get_attachment_image_src($image->ID, $size);
            ?><img src="<?php echo $attachment[0]; ?>" alt="" /><?php

Everything is already setup for admin-ajax.php.

share|improve this question
It depends on what you're doing with it on the front-end. Are you iterating through them via JS or just dumping a block of HTML? – Brian Fegter Aug 22 '12 at 4:06
Probably should stick to your original duplicate posting: wordpress.stackexchange.com/questions/62466/… – Brian Fegter Aug 22 '12 at 4:07
I'm using it as a block of HTML but I guess it would be better to iterate through jQuery? – Gab Aug 23 '12 at 21:18
Why did you delete the original question that was already a duplicate and now asking the same thing again? – kaiser Sep 24 '12 at 1:48
The first question was not as well explained. The proof is that I got an answer for this one not the previous one. – Gab Sep 26 '12 at 20:32
up vote 0 down vote accepted

Not sure if the get_all_images() function is the one that is added to your wp_ajax_{action} hook. If it is you will want to output a string back to your js. I would define a variable and concatenate the img html to it as you loop through your images.

function get_all_images() {
//your code
$response = '';
foreach($images as $image) {
        $attachment=wp_get_attachment_image_src($image->ID, $size);

        $response .= '<img src="'.$attachment[0].'" alt="" />';

 die( json_encode( $response ) );

share|improve this answer
Thank you very much! – Gab Aug 22 '12 at 21:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.