get_post_gallery()
Check a specified post's content for gallery and, if present, return the first
Uses: get_post_galleries()
Used By: get_post_gallery_images()
1 time — 0.014229 sec (extremely slow) | 50000 times — 612.03 sec (extremely slow) | PHP 7.0.4, WP 4.4.2
Hooks from the function
Return
String|Array
. Gallery data and srcs parsed from the expanded shortcode.
Usage
get_post_gallery( $post, $html );
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: global $post - $html(true|false)
- Whether to return HTML or data.
Default: true
Examples
#1 Get the first gallery of post 2179
$gal = get_post_gallery( 2179, false ); /* $gal will contain Array ( [ids] => 6790,6789,6788 [src] => Array ( [0] => http://wp-kama.ru/wp-content/uploads/2016/02/image12-80x80.png [1] => http://wp-kama.ru/wp-content/uploads/2016/02/image11-80x80.png [2] => http://wp-kama.ru/wp-content/uploads/2016/02/image10-80x80.png ) ) */
Now let's set second parameter as true ($html = true):
$gal = get_post_gallery( 2179, true );
$gal will contain the gallery HTML string:
<div id='gallery-1' class='gallery galleryid-19 gallery-columns-3 gallery-size-thumbnail'><figure class='gallery-item'> <div class='gallery-icon landscape'> <a href='/article/sajt-na-konstruktore-wix/image12'> <img width="80" height="80" src="/wp-content/uploads/2016/02/image12-80x80.png" class="attachment-thumbnail size-thumbnail" alt="image12" /></a> </div></figure><figure class='gallery-item'> <div class='gallery-icon landscape'> <a href='/article/sajt-na-konstruktore-wix/image11'> <img width="80" height="80" src="/wp-content/uploads/2016/02/image11-80x80.png" class="attachment-thumbnail size-thumbnail" alt="image11" /></a> </div></figure><figure class='gallery-item'> <div class='gallery-icon landscape'> <a href='/article/sajt-na-konstruktore-wix/image10'> <img width="80" height="80" src="/wp-content/uploads/2016/02/image10-80x80.png" class="attachment-thumbnail size-thumbnail" alt="image10" /></a> </div></figure> </div>
#2 Output each image in a gallery
<?php /* The loop */ while ( have_posts() ) : the_post(); if ( $gallery = get_post_gallery( get_the_ID(), false ) ) : // Loop through all the image and output them one by one. foreach ( $gallery['src'] AS $src ) { ?> <img src="<?php echo $src; ?>" class="my-custom-class" alt="Gallery image" /> <?php } endif; endwhile; ?>
Changelog
Since 3.6.0 | Introduced. |
get_post_gallery() get post gallery code WP 6.4.1
function get_post_gallery( $post = 0, $html = true ) { $galleries = get_post_galleries( $post, $html ); $gallery = reset( $galleries ); /** * Filters the first-found post gallery. * * @since 3.6.0 * * @param array $gallery The first-found post gallery. * @param int|WP_Post $post Post ID or object. * @param array $galleries Associative array of all found post galleries. */ return apply_filters( 'get_post_gallery', $gallery, $post, $galleries ); }