I'm using CMB2 to enable me to add custom images to a WordPress post via a File field type. Rather than have a user create a gallery and place it within the body of content, I wanted to control where and how it displayed.
<?php
// Tiled Photo Gallery
// - - - - - - - - - - - - - - - - - -
// Place outside of loop on single.php / page.php / or custom template where you want it to appear.
// I'm using this with CMB2 - https://github.com/WebDevStudios/CMB2, but it's not required.
// check for any image attachments to current post
$attachments = get_children(
array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $post->ID
)
);
// If there's more than 1 image attachment, proceed:
if( count( $attachments ) > 1 ) :
$post_thumbnail_id = '';
$exclude_feature = '';
// If it's the featured image, we don't want it displaying in this gallery. This sets it up to be excluded.
if ( has_post_thumbnail() ) :
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
$exclude_feature = ' exclude="' . $post_thumbnail_id. '"';
endif;
echo '<aside id="tf--features" class="tf--widget">';
echo ' <h3 class="widget-title">Photo Gallery</h3>';
echo do_shortcode( '[gallery size="thumbnail" type="rectangular" ' . $exclude_feature . ']' );
// If id, include, exclude are not provided, [gallery] defaults to whatever's attached to current post.
// WordPress Gallery Shortcode: codex.wordpress.org/Gallery_Shortcode
// OTHER OPTIONS: itemtag="dl" icontag="dt" captiontag="dd" link="file" size="medium" columns="4" type="slideshow"
// type="rectangular" requires Jetpack Tile Galleries. http://jetpack.me
echo '</aside>';
endif;
?>