WordPress.org

Ready to get started?Download WordPress

Forums

"gallery" display order with wp_get_attachment_image (2 posts)

  1. Kampflebkuchen
    Member
    Posted 2 years ago #

    Hello everybody,
    is there a way to sort attachments to a post similar to the gallery tab that shows the images connected to a post?

    I want to change the order in the "gallery" tab and the query below should change the order of the posted attachments accordingly.

    this is the code I am using:

    <?php
      $CP =  $post->ID
    ?>
    <?php query_posts('p=' . $CP . ''); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();    
    
     $args = array(
       'post_type' => 'attachment',
       'numberposts' => -1,
       'orderby'       => 'name',
       'post_status' => null,
       'post_parent' => $post->ID
      );
    
      $attachments = get_posts( $args );
         if ( $attachments ) {
            foreach ( $attachments as $attachment ) {
    			echo '<li><p>';
               	echo wp_get_attachment_image( $attachment->ID, array(746,500) );
    			echo '</p></li>';
              }
         }
    
     endwhile; endif; ?>

    I know there is no such thing as:
    'orderby' => 'gallery order',
    but I hope you understand what I am searching for.

  2. Inmo
    Member
    Posted 2 years ago #

    I came up against this same situation today I think.

    First thing to do is to add the the following parameter to the $args array that you are passing to get_posts()...

    'orderby' => 'menu_order'

    This will sort the returned array of attachments in relation to the gallery order you're requesting (if I've understood correctly).

    However, when you do the above you'll notice that the results are actually output in descending gallery order which is the inverse of how they are presented in the gallery admin panel. To rectify this and make everything nice and user friendly you just need to reverse the get_posts() array that's returned, before you pass it through the foreach construct.

    So to take your example...

    http://pastebin.com/cJCGAt6e

Topic Closed

This topic has been closed to new replies.

About this Topic