Skip to content

Instantly share code, notes, and snippets.

@kjbenk
Created May 2, 2017 15:02
Show Gist options
  • Save kjbenk/c6e740049d8ed42181171dec2782ad1e to your computer and use it in GitHub Desktop.
Save kjbenk/c6e740049d8ed42181171dec2782ad1e to your computer and use it in GitHub Desktop.
WordPress: Get Post Gallery Image IDs
<?php
/**
* Retrieves the image ids from a gallery.
*
* @param int|WP_Post $post Post ID or object.
* @return array An array of image ids.
*/
function get_gallery_image_ids( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return array();
}
if ( ! has_shortcode( $post->post_content, 'gallery' ) ) {
return array();
}
$images_ids = array();
if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$data = shortcode_parse_atts( $shortcode[3] );
if ( ! empty( $data['ids'] ) ) {
$images_ids = explode( ',', $data['ids'] );
}
}
}
}
return $images_ids;
}
@luiseduardobraschi
Copy link

<?php
if ( get_post_gallery() ) :

    //Get the gallery object
    $gallery = get_post_gallery( get_the_ID(), false );

    //Form an array with the found ids
    $gallery_attachment_ids = explode( ',', $gallery['ids'] );

endif;

https://wordpress.stackexchange.com/questions/221733/how-to-get-id-of-images-used-in-gallery

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment