get_post_galleries

Retrieves galleries from the passed post's content.

Description

(array) get_post_galleries( (int|WP_Post) $post, (bool) $html = true ); 

Returns (array)

A list of arrays, each containing gallery data and srcs parsed from the expanded shortcode.

Parameters (2)

0. $post (int|WP_Post)
Post ID or object.
1. $html — Optional. (bool) => true
Whether to return HTML or data in the array. Default true.

Usage

  1. if ( !function_exists( 'get_post_galleries' ) ) { 
  2. require_once ABSPATH . WPINC . '/media.php'; 
  3.  
  4. // Post ID or object. 
  5. $post = null; 
  6.  
  7. // Optional. Whether to return HTML or data in the array. Default true. 
  8. $html = true; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = get_post_galleries($post, $html); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/media.php  
  1. function get_post_galleries( $post, $html = true ) { 
  2. if ( ! $post = get_post( $post ) ) 
  3. return array(); 
  4.  
  5. if ( ! has_shortcode( $post->post_content, 'gallery' ) ) 
  6. return array(); 
  7.  
  8. $galleries = array(); 
  9. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) { 
  10. foreach ( $matches as $shortcode ) { 
  11. if ( 'gallery' === $shortcode[2] ) { 
  12. $srcs = array(); 
  13.  
  14. $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );  
  15. if ( ! is_array( $shortcode_attrs ) ) { 
  16. $shortcode_attrs = array(); 
  17.  
  18. // Specify the post id of the gallery we're viewing if the shortcode doesn't reference another post already. 
  19. if ( ! isset( $shortcode_attrs['id'] ) ) { 
  20. $shortcode[3] .= ' id="' . intval( $post->ID ) . '"'; 
  21.  
  22. $gallery = do_shortcode_tag( $shortcode ); 
  23. if ( $html ) { 
  24. $galleries[] = $gallery; 
  25. } else { 
  26. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER ); 
  27. if ( ! empty( $src ) ) { 
  28. foreach ( $src as $s ) { 
  29. $srcs[] = $s[2]; 
  30.  
  31. $galleries[] = array_merge( 
  32. $shortcode_attrs,  
  33. array( 
  34. 'src' => array_values( array_unique( $srcs ) ) 
  35. ); 
  36.  
  37. /** 
  38. * Filters the list of all found galleries in the given post. 
  39. * @since 3.6.0 
  40. * @param array $galleries Associative array of all found post galleries. 
  41. * @param WP_Post $post Post object. 
  42. */ 
  43. return apply_filters( 'get_post_galleries', $galleries, $post );