0

I am using this function to retrieve the first image from a gallery in a post.

However this doesn't work properly when I re-order the images in the gallery. It is stuck with the first image at the first time of the upload.

Any other ideas on always getting the first image as shown in the gallery?

function echo_first_image ($postID)
{                   
$attachments = get_children(
                            array(
                                  'numberposts' => -1,
                                  'order'=> 'ASC',
                                  'post_mime_type' => 'image',
                                  'post_parent' => get_the_ID(),
                                  'post_type' => 'attachment'
                                  ));

               $first_attachment = reset($attachments);
               //$last_attachment  = end($attachments); or last image
               echo wp_get_attachment_image($first_attachment->ID, 'full');
}

1 Answer 1

1

Hmm that looks familiar ;)

You are missing the orderby parameter, in this case you want to order by menu_order. Also there is no reason to query all the data using -1 when you just want one image returned so instead use 1.

$attachments = get_children(
             array(
                   'numberposts' => 1,
                   'order'=> 'ASC',
                   'post_mime_type' => 'image',
                   'orderby'        => 'menu_order',
                   'post_parent' => get_the_ID(),
                   'post_type' => 'attachment'
                   ));
1
  • just what i wanted !
    – JoaMika
    Jan 18, 2014 at 13:51

Your Answer

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

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