Add a Responsive Lightbox to Your WordPress Theme

Add a Responsive Lightbox to Your WordPress Theme

Tutorial Details
  • Difficulty: Beginner
  • Estimated Completion Time: 20 minutes

After my recent tutorial where I showed you how to Add a Responsive jQuery Slider to Your WordPress Theme, I thought I’d show you how to add a responsive lightbox to your WordPress site.

We’re going to be using the incredible fancyBox jQuery plugin (script) to demonstrate the implementation of the lightbox, but the same principles can apply to most lightbox scripts. This tutorial is going to be primarily taught through a 15-minute screencast, but I’ve also included some brief written instructions too.


The Screencast


Step 1 Include the Files

First thing we need to do is download fancyBox from the fancyBox website. We then want to open up the source folder, where we’re going to copy the following files to our theme (note that we’re using WordPress’ default Twenty Twelve theme):

  • blank.gif
  • fancybox_loading.gif
  • fancybox_overlay.png
  • fancybox_sprite.png
  • jquery.fancybox.css
  • jquery.fancybox.pack.js

It’s best to stay organised though, so let’s create a folder in our theme’s inc directory called lightbox, and in there we’ll create three new folders: css, js and images. At this point you also need to create a file called lightbox.js (don’t worry about it just yet). We then need to split up the files above into their appropriate locations, so it’ll look like the image below.

You’ll need to edit the paths to images in jquery.fancybox.css so it matches our new file structure. You can do so by doing a search and replace for:

url(' with url('../images/


Step 2 Enqueue Lightbox Files

Now that we’ve got the folder above filled with all the required files, we need to actually load them! Open up your functions.php file and add in the following:

// Enqueue Scripts/Styles for our Lightbox
function twentytwelve_add_lightbox() {
	wp_enqueue_script( 'fancybox', get_template_directory_uri() . '/inc/lightbox/js/jquery.fancybox.pack.js', array( 'jquery' ), false, true );
	wp_enqueue_script( 'lightbox', get_template_directory_uri() . '/inc/lightbox/js/lightbox.js', array( 'fancybox' ), false, true );
	wp_enqueue_style( 'lightbox-style', get_template_directory_uri() . '/inc/lightbox/css/jquery.fancybox.css' );
}
add_action( 'wp_enqueue_scripts', 'twentytwelve_add_lightbox' );

What we’ve done above is enqueued the FancyBox minified script (and by dependency, WordPress’ included jQuery library), our new lightbox.js file, as well as FancyBox’s stylesheet. Too easy!


Step 3 Initializing The Lightbox

Remember that lightbox.js file we created earlier? Time to open it up and fill it with some beautiful jQuery! In the screencast above I showed you each example separately so you could better understand how the jQuery actually worked, but below is all of the code combined. Copy this to the lightbox.js file:

(function($) {

	// Initialize the Lightbox for any links with the 'fancybox' class
	$(".fancybox").fancybox();

	// Initialize the Lightbox automatically for any links to images with extensions .jpg, .jpeg, .png or .gif
	$("a[href$='.jpg'], a[href$='.png'], a[href$='.jpeg'], a[href$='.gif']").fancybox();

	// Initialize the Lightbox and add rel="gallery" to all gallery images when the gallery is set up using  so that a Lightbox Gallery exists
	$(".gallery a[href$='.jpg'], .gallery a[href$='.png'], .gallery a[href$='.jpeg'], .gallery a[href$='.gif']").attr('rel','gallery').fancybox();

	// Initalize the Lightbox for any links with the 'video' class and provide improved video embed support
	$(".video").fancybox({
		maxWidth		: 800,
		maxHeight		: 600,
		fitToView		: false,
		width			: '70%',
		height			: '70%',
		autoSize		: false,
		closeClick		: false,
		openEffect		: 'none',
		closeEffect		: 'none'
	});

})(jQuery);
Tip: You should only really include the parts of the code above that you need. I’ve only included everything so you can see the different options for initializing the lightbox.

Step 4 Usage

You can now use the Lightbox! With the above code it’s set up to automatically add a lightbox for all links to image files with .jpg, .jpeg, .png or .gif extensions. So the following bit of code would produce a lightbox:

<a href="image.jpg"><img src="image_thumbnail.jpg" /></a>

Lightbox Galleries:

You can also create a ‘lightbox gallery’ by adding the same rel attribute to several links, like so:

<a href="image1.gif" rel="some-photos">
   <img src="image1_thumbnail.gif" />
</a>

<a href="image2.png" rel="some-photos">
   <img src="image2_thumbnail.png" />
</a>

<a href="image3.jpg" rel="some-photos">
   <img src="image3_thumbnail.jpg" />
</a>

<a href="image4.jpeg" rel="some-photos">
   <img src="image4_thumbnail.jpeg" />
</a>

However, that same lightbox gallery can also be achieved by just inserting a plain old WordPress Gallery into your post or page. Just be sure to link the thumbnails to the image files like so:

Video Lightbox:

Also included is video lightbox support, which can be achieved by linking to a video’s IFRAME embed URL (find it by looking at a video’s embed code from a service like YouTube or Vimeo) and giving it a class of video and fancybox.iframe, like so:

<a href="http://player.vimeo.com/video/50006726?badge=0" class="video fancybox.iframe">
	Click this to open up a Video from Vimeo!
</a>

IFRAME Lightbox:

In addition to IFRAMEs in video lightboxes you can embed other IFRAMES, such as Google Maps, by including the same video and fancybox.iframe classes, like the following:

<a class="video fancybox.iframe" href="http://maps.google.com/?output=embed&f=q&source=s_q&hl=en&geocode=&q=London+Eye,+County+Hall,+Westminster+Bridge+Road,+London,+United+Kingdom&hl=lv&ll=51.504155,-0.117749&spn=0.00571,0.016512&sll=56.879635,24.603189&sspn=10.280244,33.815918&vpsrc=6&hq=London+Eye&radius=15000&t=h&z=17">Google Maps (IFRAME)</a>

Captions:

As you can see in the video, some of the images I automatically inserted and applied a lightbox to have captions. These are determined by the title attribute of the link. So for example, see the captions being set in the following piece of code:

<a href="an-image.jpg" title="Here is a caption! How exciting!"><img src="an-image_thumbnail.jpg" /></a>
<a href="another-image.jpg" title="Did you see the caption on that image? Damn!">Click for an image!</a>

License

Note that FancyBox is licensed under a Creative Commons Attribution-NonCommercial 3.0 license, which means that you can use it freely in non-commercial works with attribution, but you must pay a license fee to use it in commercial projects. You can read more about the license here.


Resources


Download

If you download the source files above, please take note that after placing it in your theme’s inc directory, you’ll need to add the code found in Step 2 to your functions.php file, which enqueues jQuery and all of the fancyBox files.

Alternatively, I also turned this into a free plugin that you can download over on my personal site.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • javiervd1

    For some reason I’m digging the pictures of the monitor instead of screenshots :)

  • Pingback: WordPress – implemente Lightbox em seu layout - Noticias em tempo real

  • http://www.wpcustoms.net/ Gerald@WPcustoms

    nie tutorial and easy to follow.
    side note: change rel=”something” to data-fancybox-group=”something” to pass w3c validator.

    • bryceadams
      Author

      Cheers! And yeah, good point!

  • http://nathanrjones.com/ Nathan Jones

    Great tutorial, I was just about to work through building this myself.

  • http://twitter.com/ableslayer Mark Joseph Lape

    this is sick. I really love it. I love to insert and use the gallery on wordpress itself without having to use any other plugins. Anyway, you say this is responsive, on a mobile phone, you really dont want users to click on the lightbox right. Cuz it wont make any sense to for the reason that its large already w/0 the lightbox. Is there anyway that will disable the links to an image going to a lightbox when in mobile viewport? Thanks for this.

  • http://www.mojowill.com/ theMojoWill

    Nice tutorial, also loving the pictures of the screen instead of code extracts ;)

  • Pingback: Qoozon » Cool Stuff For Web Designers #5

  • http://www.facebook.com/people/Artur-Swoboda/100000416915744 Artur Swoboda
    • http://twitter.com/bryceadams Bryce Adams

      Sorry just saw this. Honestly no idea about IE compatibility. What browser/version is it exactly?

  • http://www.facebook.com/ssellek1 Sean Sellek

    Your Adobe apps seem to really want to be updated…

  • Pingback: Add Responsive Lightbox to WordPress | Tri Nguyen

  • Pingback: TOP 5 USEFUL WORDPRESS TUTORIALS | Free WordPress Themes and Plugins

  • http://twitter.com/Caparico Kobi Ben Itamar

    I really enjoyed this, as it was useful and well explained. Thank you!

    It is working great for me on Chrome and on IE (version 9 / 8 / 7).

  • Pingback: Tweet Parade (no.46 Nov 2012) | gonzoblog

  • vind

    Is there any easy way to make this lightbox look like this? I’m dying to find a lightweight responsive jQuery lightbox with video support and the very specific black theme that Lightbox 2 used to have. I’m not a coder myself, so that alone has been calling for struggle in the absence of what I want. However, if someone may want to help me out, I can at least edit some code by given instructions…

  • http://twitter.com/pushplaybang Paul van Zyl

    I keep getting a blank overlay and console errors, anyone else having this problem ?

    the error is :

    Uncaught Error: HIERARCHY_REQUEST_ERR: DOM Exception 3

    • http://twitter.com/pushplaybang Paul van Zyl

      fancy box now works fantastically, as long as I dont register and enqueue modernizr, which is a bit sh*t – anyone else had this issue ? contacted the fancybox author, and he’s a little less than interested….

  • Akeisa Lowe

    How can I use YouTube’s iframe instead of just a simple link that opens the video?

  • http://bahassi.com/ Diseñador Web Valencia

    This is just What I was looking for. thanks a lot for the tip.

  • Walker Talker

    Any tutorial like this for Lightbox2? http://lokeshdhakar.com/projects/lightbox2/

  • disqus_kBUYiJc2OO

    Awesome tutorial…it worked in my theme..!!!!

  • Kang Iwan

    Huh, after searching for hours, this tutorial which finally really work.. :D

    Thanks very much Sir.. Now, I’ll try to add text and link below the fancybox, do you have idea how to do this?? :)

  • Pingback: 20 Useful WordPress Theme Tutorials and Resources - Streetsmash

  • Lionel Cares

    can anyone help me with this – i am a first time wordpress user and when i installed all this it does not work, do i have to include style references where the image references are above them.

  • http://twitter.com/ActualGabe Gabriel Luethje

    I’m still trying to find a lightweight responsive lightbox that’s simple and just works. I like fancybox, but the script alone is 23k minified, which is pretty heavy.

    I always like shadowbox, until I realized it’s 37k minified.

    I have a slider script (Flexslider), a tabs script (Chris Coiyer’s Organic Tabs), Sooth Scroll and my uiliity scripts all concatenated and minified together to a 24k js file. Where is the simple, lightweight lightbox script I’m looking for??

    Maybe I should just stop worrying about it. After all, 23k is about what a small image weighs…I just like to be careful about adding this and that carelessly to my pages.

    • http://twitter.com/ActualGabe Gabriel Luethje

      Now this is what I’m talking about: http://tutorialzine.com/2012/04/mobile-touch-gallery/

      TouchTouch is 6k / 2k minified, with a 3k (non minified) CSS file. It is responsive and it has the big bonus of touch support, so you can swipe through galleries on the mobile devices.

      I just incorporated it into a WordPress site I’m building and it works quite well.

      • http://twitter.com/DJYouso Youso

        Did you get this to work? Are you using it with WordPress? Got a tutorial for that?

  • http://www.facebook.com/wsieben Jonathan Robrecht

    I did everything like in the tutorial, i finaly downloaded the sourcecode just too see if i did some mistakes within the code. However all my slide images get displayed below each other… it seems that he doesnt load the script but if i load the script form the header.php all images are displayed none …ideas?

  • Aimee

    Just finished installing this. Thank you! A note, when using Twenty Twelve theme/ WordPress 3.5.1, I could not get the gallery to load as Fancybox (though single images were fine). It turns out even though I set the gallery to “link to media file”. I had to save them as “link to attachment page”, update the page, and then change BACK “link to media file”, and update again before it would work. Not sure why. But it worked.

  • Sayeman Islam

    Fantastic Tutorial as always!
    Thanks Bryce.

  • http://eglashcreative.com/ Joe Eglash

    This has worked great for me – thanks so much. I just discovered a problem, for me, though – it worked perfectly, but was overwritten when I updated my WP theme (Pagelines Framework). So I then tried to install the files in a Pageline Customize folder, where a functions.php file resides that does not get overwritten. I’ve changed all files appropriately, but I cannot get the thing to work again. Could there a problem in where I’m storing the files and how I’m pointing to them? Thanks again.

    • http://eglashcreative.com/ Joe Eglash

      Ah, commenting on my own comment.

      I’ve fixed this. There was a PHP error, unrelated. Thanks.