Get a Page’s attachments in Gallery order

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("https://wordpress.stackexchange.com/".$regex."https://wordpress.stackexchange.com/",$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);
  }
}

Leave a Comment