0

I created the foreach loop to display post images, but It displays them from last to first, how can I make It to displays from first to last ;) ?

     <?php $args = array(
     'post_type' => 'attachment',
    'numberposts' => -1,
      'post_status' => null,
       'post_parent' => $post->ID
     );

     $attachments = get_posts( $args );

 if ( $attachments ) {
   foreach ( $attachments as $attachment ) : ?>
   <p>                    
      <?php echo wp_get_attachment_image( $attachment->ID, 'full' ); ?>
      </p>

   <?php endforeach;    

 }
   ?>
2

Why wouldn't you just pull them in the order you need instead of reversing the array?

$args = array(
  'post_type' => 'attachment',
  'posts_per_page' => -1, // correct key is posts_per_page, not numberposts
  'orderby' => 'date'
  'order' => 'ASC',
  'post_parent' => $post->ID
);

$attachments = get_posts( $args );
  • I don't think post_date is a possible order field, I think you meant date. I also wonder why you use post_status as null instead of inherit. But I agree with you on the method (+1) ;-) – birgire Jun 26 '14 at 21:54
  • Hm, but if I use post date, won't It show from the last one to the first ;) ? – Mateusz Winnicki Jun 26 '14 at 22:04
  • @ birgirie. You're correct, orderby should be 'date'. Updated. Re post_status: I copy/pasted the query posted by the OP- figured the null value wasn't hurting anything so left it alone. It should probably just be removed since WordPress will select the appropriate status anyway: github.com/WordPress/WordPress/blob/master/wp-includes/… – Joey Yax Jun 26 '14 at 22:36
0

Re-reverse the array!

     if ( $attachments ) {

$attachments = array_reverse( $attachments );

       foreach ( $attachments as $attachment ) : ?>
       <p>                    
          <?php echo wp_get_attachment_image( $attachment->ID, 'full' ); ?>
          </p>

       <?php endforeach;    

     }
  • So easy ;) Hm, but can you explain me, why It works this way ? I mean, why does It takes from last element instead of first ? – Mateusz Winnicki Jun 26 '14 at 21:28
  • 1
    WP always returns posts (including attachments) with the most recent first, by default. You could also pass order and orderby arguments in your get_posts to change this if you wanted. – vancoder Jun 26 '14 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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