Using WordPress ‘get_post_gallery()’ PHP function

The get_post_gallery() WordPress PHP function checks a specified post’s content for a gallery, and if present, returns the first one.

Usage

get_post_gallery($post, $html);
  • Input: $post (int|WP_Post, optional) – Post ID or WP_Post object. Default is global $post.
  • Output: $html (bool, optional) – Whether to return HTML or data. Default is true.

Parameters

  • $post (int|WP_Post, optional) – Post ID or WP_Post object. Default is global $post.
  • $html (bool, optional) – Whether to return HTML or data. Default is true.

More information

See WordPress Developer Resources: get_post_gallery()

Examples

This example displays a gallery from a specified post.

if ( $gallery = get_post_gallery( get_the_ID() ) ) :
  echo $gallery;
endif;

This example loops through all images in a gallery and outputs them with a custom image class.

if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :
  foreach ( $gallery['src'] AS $src ) {
    echo '<img src="' . $src . '" class="my-custom-class" alt="Gallery image" />';
  }
endif;

This example retrieves the image IDs of a gallery.

if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :
  $image_ids = explode( ',', $gallery['ids'] );
  print_r( $image_ids );
endif;

This example displays the gallery images with their respective captions.

if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :
  foreach ( $gallery['src'] as $key => $src ) {
    echo '<img src="' . $src . '" alt="' . $gallery['caption'][ $key ] . '" />';
  }
endif;

This example retrieves the total number of images in a gallery.

if ( $gallery = get_post_gallery( get_the_ID(), false ) ) :
  $total_images = count( $gallery['src'] );
  echo 'Total Images: ' . $total_images;
endif;