Make Images appear in the same order as in media browser using get children?

I would really like my images to display in the same way I’ve ordered them in the media browser. What am I doing wrong?

$images =& get_children( array('post_parent' => $post->ID,
                                               'post_type' => 'attachment',
                                               'post_mime_type' => 'image',
                                               'orderby' => 'menu_order',
                                               'order' => 'asc' ));

Related posts

Leave a Reply

1 comment

  1. a) If you have reordered the images under the uploaded to this post in the media browser then they should have menu_order>0 and you can get that order with

    'orderby' => 'menu_order',                                               
    'order' => 'asc' 
    

    b) If you haven’t, then menu_order=0 for all these images and you will need to use

    'orderby' => 'ID',                                               
    'order' => 'asc' 
    

    to get the same order (or date asc).

    A solution for both cases could be like this, in pure SQL:

    ... ORDER BY menu_order ASC, ID ASC
    

    If you try

    'orderby' => 'menu_order ID',                                               
    'order' => 'asc' 
    

    you will get

    ... ORDER BY menu_order, ID ASC
    

    Since get_children() is using get_posts() there are some restriction on how extra fields can be added to the orderby and order parameters .

    You can also use your custom query, where you have full control over the double ordering:

    $sql="SELECT {$wpdb->posts}.* 
    FROM {$wpdb->posts} 
    WHERE {$wpdb->posts}.post_parent = %d  
    AND ({$wpdb->posts}.post_mime_type LIKE 'image/%%')  
    AND {$wpdb->posts}.post_type = 'attachment' 
    AND ({$wpdb->posts}.post_status <> 'trash' AND {$wpdb->posts}.post_status <> 'auto-draft')  
    ORDER BY {$wpdb->posts}.menu_order ASC,{$wpdb->posts}.ID ASC";
    
    $images=$wpdb->get_results($wpdb->prepare($sql,$post->ID));