1. Code
  2. WordPress

Quick Tip: Integrating Colorbox Into the Native [gallery] Shortcode


The native [gallery] shortcode is nice, but not great. In this quick tip, we're going to beautify it with jQuery.

The [gallery] shortcode is not great. You can't disable its default CSS, you can't add or edit the CSS classes, you can't edit the default attributes (which is actually a general shortcode problem)... Although this stuff doesn't bother the majority of WordPress developers, weirdos like me could complain! :)

In this quick tip, we're going to get rid of the image attachment pages and let our sites' visitors navigate through the images within a jQuery modal box.

One of the Best jQuery Lightbox Plugins Available: ColorBox

With less than 5KB (gzipped) and a wide range of browser support (which even includes IE6), Colorbox is my favourite jQuery lightbox plugin.

As you can see from the plugin's page, it has loads of settings, methods and hooks so you can customize it any way you want. It also has 5 neat CSS-based themes.

Download the pack and extract colorbox.min.js and one of the 5 themes (the colorbox.css file and the "images" folder) into a folder called "colorbox" and upload that folder to your WordPress theme. Add the following code at the end of the colorbox.min.js file before uploading:

Shortcode-Ception: Building a Shortcode Which Uses Another Shortcode

I know that this is going to be a little bit weird, but it seems to be the cleanest way. We're going to create the [jgallery] shortcode.

Tip Within the Quick Tip: If you plan to change all the gallery shortcodes in your posts after creating the [jgallery] shortcode, I recommend using the Search Regex plugin to search/replace [gallery] with [jgallery].

Like always, we'll begin with creating the base shortcode function:

Next, we will enqueue the CSS and the JS files. Don't forget, jQuery will be enqueued automatically (if it's not already), by specifying that the Colorbox script depends on it.

Everything is ready, except we need to use the [gallery] shortcode inside this function. We will use the do_shortcode() function and return the [gallery link="file"] shortcode:

All done! After adding this function into the functions.php file of your theme, you can start using the [jgallery] shortcode right away. Let us know what you think in the comments below. Enjoy! :)

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.