Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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) {

$output;
$output_row;

$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

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();

  preg_match_all('/'.$regex.'/',$post->post_content,$matches);

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

  if (!empty($attr['ids'])) {
    $atts = new WP_Query(
      array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'post__in' => explode(',',$attr['ids']),
        'orderby' => 'post__in'
      )
    );
    var_dump($atts);
  }
}
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

 
discard

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.