Extract Gallery picture info from empty gallery shortcode

I don’t like how WordPress processes the gallery shortcode.

This is some slightly modified code I had that I’ve used to get the images in a gallery. In this example, the attachments (and thus their IDs) would only be available after the gallery shortcode has been processed.

If you’re looking to display different HTML than the default gallery, I’d use the post_gallery filter to short-circuit the built-in WordPress shortcode and display your own.

namespace StackExchange\WordPress;

class Q291678 {
   protected $attachements = [];
   public function getAttachments() : array {
     return $this->attachments;
   }
   public function wp_loaded() {
     \add_filter( 'shortcode_atts_gallery', [ $this, 'shortcode_atts_gallery' ], 10, 4 );
   }
   public function shortcode_atts_gallery( array $out, array $pairs, array $atts, string $shortcode ) : array {
     $this->attachements = $this->getPostAttachments( $out );
     return $out;
   }
   protected function getPostAttachments( array $atts ) : array {
     //* Code copied from WP Core to get post attachements
     $id = intval( $atts[ 'id' ] );
     if ( ! empty( $atts[ 'include' ] ) ) {
         $_attachments = \get_posts( [
           'include'        => $atts[ 'include' ],
           'post_status'    => 'inherit',
           'post_type'      => 'attachment',
           'post_mime_type' => 'image',
           'order'          => $atts[ 'order' ],
           'orderby'        => $atts[ 'orderby' ]
         ] );

         $attachments = [];
         foreach ( $_attachments as $key => $val ) {
             $attachments[ $val->ID ] = $_attachments[ $key ];
         }
     } elseif ( ! empty( $atts['exclude'] ) ) {
         $attachments = \get_children( [
           'post_parent'    => $id,
           'exclude'        => $atts[ 'exclude' ],
           'post_status'    => 'inherit',
           'post_type'      => 'attachment',
           'post_mime_type' => 'image',
           'order'          => $atts[ 'order' ],
           'orderby'        => $atts[ 'orderby' ]
         ] );
     } else {
         $attachments = \get_children( array( 
           'post_parent'    => $id, 
           'post_status'    => 'inherit',
           'post_type'      => 'attachment',
           'post_mime_type' => 'image',
           'order'          => $atts[ 'order' ],
           'orderby'        => $atts[ 'orderby' ] ) );
     }
     //* End code from core
     return $attachments;
   }
}
\add_action( 'wp_loaded', [ new Q291678, 'wp_loaded' ] );