Dimics

Learn everything you want to know. Graphic and web tutorials.

Make The WordPress Gallery functional

Since version 3.5 WordPress has a native feature for creating media galleries. This works great in the back-end but doesn’t look that great on the page. It just displays a grid of images without any functionality. To make The WordPress Gallery functional and look more like a gallery we are going to write a WordPress plugin that uses a jQuery plugin and some styles to add functionality and styling to this native gallery.

 

The WordPress Gallery

Before we start our plugin it’s good to take a look at the gallery, how to create and insert it in to a page. WordPress has a page explaining this:

http://codex.wordpress.org/The_WordPress_Gallery

For our plugin to work it’s important to select “Media file” to link to.

 

Basic plugin

First we need a basic template for our plugin, an easy tool for generating this is: http://starter.pixelgraphics.us/

When you fill in the plugin name and optional some other settings you get a basic template which is a good starting point for a jQuery plugin.

(function($){
    $.DWPGallery = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        
        // Add a reverse reference to the DOM object
        base.$el.data("DWPGallery", base);
        
        base.init = function(){
            base.options = $.extend({},$.DWPGallery.defaultOptions, options);
            
            // Put your initialization code here
        };
        
        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        // 
        // };
        
        // Run initializer
        base.init();
    };
    
    $.DWPGallery.defaultOptions = {
    };
    
    $.fn.dWPGallery = function(options){
        return this.each(function(){
            (new $.DWPGallery(this, options));
        });
    };
    
})(jQuery);

 

Init

When you include a WordPress gallery into a page, some basic markup is created, because it’s easier to work with we are going to generate our own markup from that. So we will have a container div, a div for the thumbnails, and a div for the selected image.

Let’s create them in the init function of our plugin:

base.init = function(){
	base.options = $.extend({},$.DWPGallery.defaultOptions, options);

	base.currentImg = 0;

	// Create the new gallery divs
	var galleryContainer = $("<div/>").addClass("DWPG_galleryContainer");
	var thumbsDiv = $("<div/>").addClass("DWPG_thumbs");
	var selectedImgDiv = $("<div/>").addClass("DWPG_selectedImg");

	// Append divs to container
	galleryContainer.append(selectedImgDiv, thumbsDiv);

	// Next steps...
};

Now we have to create some elements per image, so we need to loop through the images.

For each image we create a thumb in the thumbs div, and a bigger image for the selected image div. Also we bind a click event to the thumbnail to select the correct image.

The following code will be in the init function just were we left off.

// Loop through he gallery items
$(".gallery-item", el).each(function(item){
	// Get the full res img link from the anchor
	var imgLink = $("a", this).attr("href");

	// Prepare and append to thumbs
	$("a", this).addClass("DWPG_thumb")
	// Bind a click event to the thumb to select the image
	.bind("click", function(event){
		event.preventDefault();

		// Select the clicked image - We'll create this function later...
		base.selectImg($(this).index());

		return false;
	});

	thumbsDiv.append($("a", this));

	// Create and append the full res img to selectedImgDiv
	var fullImg = $('<img src="' + imgLink + '" />').hide();
	selectedImgDiv.append(fullImg);
	
});

Almost done with the init. Last thing we have to do is replace the WordPress markup with our fresh new fancy gallery. Also we set some references to easily address it. Last we set the default image to the first (position 0). This will be placed after the code from the last step.

// Replace the default gallery with new structure
$(el).replaceWith(galleryContainer);

// Access to jQuery and DOM versions of element
base.$el = $(galleryContainer);
base.el = galleryContainer;

// Add a reverse reference to the DOM object
base.$el.data("DWPGallery", base);

// Select the first img
base.selectImg(0);

We need one other function, the select image function we used in our code to select an image by it’s index. It hides all images and only shows the selected one, it also adds a class to the selected thumbnail.

base.selectImg = function(index){
	// Default index to 0
	if(index === undefined || index === "")
		index = 0;

	base.currentImg = index;

	// Show selected img
	$.when($(".DWPG_selectedImg img", base.el).fadeOut(100)).then(function(){
		$(".DWPG_selectedImg img", base.el).hide().eq(index).fadeIn(300);
	});

	// Remove and set class for selected thumb
	$(".DWPG_thumb", base.el).removeClass("DWPG_selectedThumb");
	$(".DWPG_thumb", base.el).eq(index).addClass("DWPG_selectedThumb");
};

That’s it. Now we only have to init the plugin onload. The WordPress galleries have a class of  “gallery” so we init the plugin to each “.gallery” when the document is loaded.

// Init plugin when page is ready
$(document).ready(function(){
	$(".gallery").dWPGallery();
});

Styles

You need to do some basic styling for it to look good, but I’ll trust you in doing that ;). In the gist on github I’ve included some simple styles to get you started.

Result

demo

Download

I’ve uploaded the file to github as a gist:

https://gist.github.com/dsdeur/08fc3a95416d0cbf1f52