Initialise different Themes within the WordPress Gallery

The build in WordPress Gallery is a great tool for editors to create easily image collections. But  it’s really limited in the theme. Therefore most people use huge gallery plugins to be able to display just a simple slider.

If you want to give your editors the opportunity to choose wether to show a slider or a great layouted gallery using the WordPress Gallery here is one solution. It can be just added in your theme functions or you can integrate the scripts in a plugin.

First we need to expand the WordPress Gallery settings with a selectbox to choose a theme like ‚default WordPress‘, ’slider‘, etc. or set a special behaviour like ‚use thickbox‘.
We are able to do this by using the print_media_templates action hook (use your favorite prefix for the functions instead of ‚prefix‘).

/* =============== expand gallery shortcode =============== */
if(is_admin()) {
	add_action('print_media_templates','prefix_media_template');
}

We use the condition is_admin(), because the hook is only needed in backend mode. Next thing to do is to build up our prefix_media_template function.

/**
 * prefix_media_template
 *
 * Adds Options to wp_media Gallery
 * @return void
 */
function prefix_media_template (){

  ?>
  <script type="text/html" id="tmpl-prefix_view_select">
	<label class="setting">
	<h3><?= __('Layout Settings', 'prefix') ?></h3>
	</label>
	
	<div id="prefix_view_settings" >

		<label class="setting">
		  <span><?= __('Layout', 'prefix') ?></span>
		  <select data-setting="prefix_gallery_layout" name="prefix_gallery_layout" id="prefix_gallery_layout">
			<option value="wordpress_default" data-plugin="wordpress_default"><?= __('Wordpress Default', 'prefix') ?></option>  
			<option value="slider"><?= __('Slider', 'prefix') ?></option>  
			<option value="custom"><?= __('Custom', 'prefix') ?></option> 
		  </select>
		</label>
		<!-- add more Settings if needed. Use Pattern above label->span->form element -->

	</div>

  </script>

  <script>
	jQuery(document).ready(function(){

	  // add your shortcode attribute and its default value to the
	  // gallery settings list;
	  // new settings defined in the html markup must appear here and fir to the Setting Element attribute data-setting 
	  _.extend(wp.media.gallery.defaults, {
		prefix_gallery_layout: 'wordpress_default',
	  });

	  // merge default gallery settings template with yours
	  wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
		template: function(view){
			return wp.media.template('gallery-settings')(view)
				+ wp.media.template('prefix_view_select')(view);	
			}
	  });

	});

  </script>
  <?php

}

This code is just jQuery and JavaScript. WordPress uses a JavaScript template engine to build the main media frame. In lines 10-29 we set up our little cutom settings area with the select option as a template element. it is defined by the id parameter ‚tmpl-‚ and recognized by the following identifier. We add this template in Lines 41-46 to the main media element. Now we must tell WordPres, that there is the new shortcode attribute ‚prefix_gallery_layout‘ and its default value. This can be easily done by extending the wp.media.gallery.defaults object in line 36-38. We just added one parameter to the settings, but you can expand our settings area with mor custom options. Dont’t forget to add them to the wp.media.gallery.defaults .

Some Code and we see the result with the new layout settings section.

gallery-settings

The new shortcode attribute is now available and can be fetched in the post_gallery filter hook to define our gallery frontend layouts by adding some lines to the first code part.

/* =============== expand gallery shortcode =============== */
if(is_admin()) {
	add_action('print_media_templates','prefix_media_template');
} else {
	add_filter( 'post_gallery', 'prefix_gallery_shortcode', 10, 4 );
}

In the new function ‚prefix_media_template‘ we can intercept the WordPress Gallery rendering and set a custom layout for each layout.

/**
 * prefix_gallery_shortcode
 *
 * Hooks into the Default Gallery Theme
 */
function prefix_gallery_shortcode( $output = '', $atts, $content = false, $tag = false ) {

	/**
	 * Here you can parse the Gallery if needed
	 *
	 * Use $atts['prefix_gallery_layout'] to detect the new Gallery Option
	 * Use vars defined in prefix_media_template()
	 */
	switch ($atts['prefix_gallery_layout']) {
		case 'slider':
			$output = 'SLIDER';
			break;
		case 'thickbox':
			$output = 'CUSTOM';
			break;
		default:
			// if no value is set, the default value 'wordpress_default' is used
			break;
	}

	return $output ;
}

That’s all. The really hard part is now to define the custom layouts. Here a short example using the bxSlider (http://bxslider.com/).

First we must expand the WordPress hook section to integrate the slider scripts

/* =============== expand gallery shortcode =============== */
if(is_admin()) {
	add_action('print_media_templates','prefix_media_template');
} else {
	add_action( 'wp_enqueue_scripts', 'prefix_fe_scripts', 40, 1);
	add_filter( 'post_gallery', 'prefix_gallery_shortcode', 10, 4 );
}

/**
 * prefix_fe_scripts
 *
 * Load FE javascript and css files
 */
function prefix_fe_scripts($hook) {
	
	global $post;

	if(isset($post->post_content) && !empty($post->post_content) && has_shortcode( $post->post_content, 'gallery' )) { 
		
		/**
		 * Here you can add Styles & Scripts if the Shortcode is used
		 *
		 * Parse Shortcodes on post_content an cycle through them
		 */			
		$pattern = get_shortcode_regex();
		preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches);
		
		foreach($matches[0] as $shortcode) {
			/**
			 * Parse Shortcode atts
			 */	
			$shortcodeAtts = shortcode_parse_atts( $shortcode );
			
			if(isset($shortcodeAtts['prefix_gallery_layout'])) {
				
				/**
				 * Custom Gallery is used
				 * Enque Scripts and styles
				 */	
				wp_enqueue_script( 'prefix_bxslider_js', plugins_url('prefix_gallery_snippet/bxSlider/jquery.bxslider.min.js'), array('jquery'), '', true );
				wp_enqueue_style( 'prefix_bxslider_css', plugins_url('prefix_gallery_snippet/bxSlider/jquery.bxslider.min.css') );
		 				 
			}
		}
	}

}

It is usefull to check if the WordPress Gallery schordcode is really used by the current post. If true, integrate the bxSlider.
Next Step: build up the gallery as bxSlider in the prefix_gallery_shortcode function.

/**
 * prefix_gallery_shortcode
 *
 * Hooks into the Default Gallery Theme
 */
function prefix_gallery_shortcode( $output = '', $atts, $content = false, $tag = false ) {

	/**
	 * Here you can parse the Gallery if needed
	 *
	 * Use $atts['prefix_gallery_layout'] to detect the new Gallery Switcher
	 * Use vars defined in prefix_media_template()
	 */	
	switch ($atts['prefix_gallery_layout']) {
		case 'slider': 
			
			// Check if images are available
			if(isset($atts['ids']) && !empty($atts['ids'])) {			
				// build slider element 
				ob_start(); ?>
				<ul class="bxslider">
				<?php foreach(explode(',', $atts['ids']) as $attachment_id) { ?>
					<li><img src="<?php echo wp_get_attachment_url($attachment_id, 'medium'); ?>" /></li>
				<?php } ?>
				</ul>
				<script>
				jQuery(document).ready(function(){
				  jQuery('.bxslider').bxSlider();
				});
				</script>
				<?php
				$output = ob_get_clean();				
			}

			break;
		case 'custom': 
			$output = 'CUSTOM';
			break;
		default:
			//
			break;
	}

	return $output ; 
} 

See the working result.

This is just a short example with the bxSlider default settings. You can do what you want an integrate your favorite gallery styles.

Here you can download the complete code with the bxSlider integration as a sample plugin: prefix_gallery_snippet.zip.

Gallery images by