Created
May 2, 2017 15:02
-
-
Save kjbenk/c6e740049d8ed42181171dec2782ad1e to your computer and use it in GitHub Desktop.
WordPress: Get Post Gallery Image IDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://wordpress.stackexchange.com/questions/221733/how-to-get-id-of-images-used-in-gallery