Skip to content

Displaying a Fancy Gallery

Jim Reevior edited this page Aug 14, 2018 · 1 revision

Displaying a Fancy Gallery

When using the gallery shortcode in the post editor, the JavaScript and CSS needed for a fancy gallery will automatically be enqueued. However, when manually outputting a gallery shortcode with do_shortcode(), there is an extra step that needs to take place.

<?php
/**
 * Enqueue the fancy gallery JS and CSS on page templates that manually output
 * the [gallery] shortcode and the front page.
 */
function mytheme_enqueue_scripts() {
	$page_templates = array(
		'page-templates/custom-template.php',
		'page-templates/custom-gallery.php',
	);

	if ( is_page_template( $page_templates ) || is_front_page() ) {
		r_enqueue_fancy_gallery();
	}
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' );

You can also include r_enqueue_fancy_gallery() in your page template, as long as you call the function before calling get_header(). Otherwise, the CSS will not be output in the header correctly.

The first method, however, is preferred because it keeps the information about which areas of the site use the fancy gallery feature in one place.

Building Your Own Gallery Shortcode

Let's consider the following example. A client wants to have a photo gallery on the home page. The design dictates that the gallery is in a different section than the editor content. To accomplish this, we can create a CMB2 File List field (which allows editors to pick the images for the gallery) and output the gallery using a function.

<?php
/**
 * Output a gallery shortcode for custom image galleries.
 *
 * @param int $post_id Post ID.
 */
function mytheme_custom_gallery( $post_id ) {
	$images = get_post_meta( $post_id, '_mytheme_custom_image_gallery', true );

	if ( empty( $images ) ) {
		return;
	}

	$image_ids = array_keys( $images );
	$gallery_args = array(
		'ids'  => $image_ids,
	);

	echo gallery_shortcode( $gallery_args );
}

Welcome to Responsive!

Get started

Configuration

Build child themes

Sass

Javascript

PHP

Shortcodes

Templates

GitHub

Tasks

Contribute to the framework

Code Examples

BU Developer Resources

Clone this wiki locally