Having created a page and a gallery within that page, I would like to retrieve all the images in that gallery in the order they are set when the gallery is created, i.e. the order which I drag them in to in the add media pop-up.

I need to retrieve all the image URLs and their captions etc into an array in PHP.

I have been using the below code, however it does not account for the order they are set in the gallery.

function get_page_attached_images($page_id) {


$thumb_ID = get_post_thumbnail_id( $page_id );

if ( $images = get_posts(array(
  'post_parent' => $page_id,
  'post_type' => 'attachment',
  'numberposts' => -1,
  'orderby'        => 'menu_order',
  'order'           => 'ASC',
  'post_mime_type' => 'image',
  'exclude' => $thumb_ID,

  foreach ( $images as $img ) {

    $output_row['url'] = $img->guid;
    $output_row['title'] = $img->post_title;
    $output_row['caption'] = $img->post_excerpt;
    //$output_row['img'] = $img;

    $output[] = $output_row;


return $output;


Does anyone know how to preserve the gallery order when retrieving these attachments?

I am using Wordpress v3.61.


1 Answer 1


Gallery "order" is saved in the gallery shortcode itself. Take a look at the code for the gallery using the "text" editor, then drag the images around, and look at the raw code again. To make this work, you will have to parse the post content for the gallery shortcode and extract its data. Something like this:

function extract_gallery_wpse_114337($post) {

  $regex = get_shortcode_regex();


  if (!empty($matches[2])) {
    foreach ($matches[2] as $k => $v) {
      if ('gallery' == $v) {
        $attr = shortcode_parse_atts($matches[3][$k]);

  if (!empty($attr['ids'])) {
    $atts = new WP_Query(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'post__in' => explode(',',$attr['ids']),
        'orderby' => 'post__in'
  • Nice one, someone has managed this too - link in my comment above should you like to check it out
    – Larry B
    Commented Sep 16, 2013 at 14:50

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.