The get_post_galleries() WordPress PHP function retrieves galleries from the passed post’s content.
Usage
get_post_galleries( $post, $html );
Example:
$galleries = get_post_galleries( 42, true );
Parameters
$post (int|WP_Post)
: Required. Post ID or object.$html (bool)
: Optional. Whether to return HTML or data in the array. Default: true.
More information
See WordPress Developer Resources: get_post_galleries()
As of WordPress 5.9, this function does support block editor galleries.
Examples
Retrieve galleries from a post
Retrieve all galleries from a specific post and display their HTML.
$post_id = 42; $galleries = get_post_galleries( $post_id, true ); foreach ( $galleries as $gallery ) { echo $gallery; }
Retrieve gallery data from a post
Retrieve all galleries from a specific post and access their data (IDs, URLs, etc.).
$post_id = 42; $galleries = get_post_galleries( $post_id, false ); foreach ( $galleries as $gallery ) { print_r( $gallery ); }
Check if a post has a gallery
Check if a post has at least one gallery.
$post_id = 42; $has_gallery = ( count( get_post_galleries( $post_id, false ) ) > 0 ); if ( $has_gallery ) { echo "This post has a gallery."; } else { echo "This post does not have a gallery."; }
Get the first gallery from a post
Retrieve the first gallery from a specific post and display its HTML.
$post_id = 42; $galleries = get_post_galleries( $post_id, true ); if ( ! empty( $galleries ) ) { echo reset( $galleries ); }
Get the number of images in a post’s galleries
Retrieve all galleries from a specific post and count the total number of images.
$post_id = 42; $image_count = 0; $galleries = get_post_galleries( $post_id, false ); foreach ( $galleries as $gallery ) { $image_count += count( $gallery['ids'] ); } echo "Total images in galleries: " . $image_count;