• 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.

Viewing 1 replies (of 1 total)
  • 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…

    https://pastebin.com/cJCGAt6e

Viewing 1 replies (of 1 total)
  • The topic ‘"gallery" display order with wp_get_attachment_image’ is closed to new replies.