WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
I had asked this Q before and turns out someone had answered - wordpress.stackexchange.com/questions/80408/… – Larry B Sep 16 '13 at 14:42

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'
share|improve this answer
Nice one, someone has managed this too - link in my comment above should you like to check it out – Larry B Sep 16 '13 at 14:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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