Adding Colorbox to Wordpress

Add a Lightbox Gallery to WordPress Posts

By -

Writing the jQuery Script

Initializing jQuery Colorbox is as easy as writing the following line of code:

[javascript]
selector.colorbox();
[/javascript]

selector stands for the HTML anchor element on which you want to apply the lightbox effect.

But, with such a highly configurable plugin, you can do a bit more. There are plenty of settings you can adjust to make Colorbox do what you want. Let’s start by tweaking some of them. Inside the jQuery no conflict wrapper, write the following code snippet:

[javascript]
//Settings for lightbox
var cbSettings = {
rel: ‘cboxElement’,
width: ‘95%’,
height: ‘auto’,
maxWidth: ‘660’,
maxHeight: ‘auto’,
title: function() {
return $(this).find(‘img’).attr(‘alt’);
}
}
[/javascript]

The code above stores a bunch of settings inside a JavaScript object literal called cbSettings:

  • rel is used to group photos together. Setting this attribute enables the navigation arrows in the lightbox so that users can move from one photo to the previous or next photo in the group. cboxElement is a class that Colorbox automatically adds to the anchor links where lightbox functionality is attached, but you’re free to group photos by a different name.
  • width and height refer to the lightbox dimensions. A percentage value for the width helps to keep the component fluid and responsive. maxWidth and maxHeight refer to the maximum width and maximum height of the content loaded in the lightbox, which in this case is the gallery photo.
  • title can be used to display a caption for the photo in the lightbox. Here it’s set to a short function that tells Colorbox to extract the value of the image’s alt attribute and use it as image caption.

You can find a list of all the available settings on the jQuery Colorbox website.

Once the settings are configured, initialize Colorbox:

[javascript]
//Initialize jQuery Colorbox
$(‘.gallery a[href$=”.jpg”],
.gallery a[href$=”.jpeg”],
.gallery a[href$=”.png”],
.gallery a[href$=”.gif”]’
).colorbox(cbSettings);
[/javascript]

The snippet above selects all the anchor tags inside the element with a class of gallery. Further, the selected anchor tags must have a href value that ends in .jpg, .jpeg, .png, or .gif (the most common image file formats). Finally, Colorbox is called on this selection passing in the cbSettingsobject as an argument.

Contemporary web design is responsive web design, therefore it’s important for us that the lightbox should adapt to all screen sizes. In view of this, add the following snippet that takes care of this crucial aspect:

[javascript]
//Keep lightbox responsive on screen resize
$(window).on(‘resize’, function() {
$.colorbox.resize({
width: window.innerWidth > parseInt(cbSettings.maxWidth) ? cbSettings.maxWidth : cbSettings.width
});
});
[/javascript]

On browser resize, the $.colorbox.resize() method is triggered. Inside this method, the code above sets the width value to a JavaScript conditional ternary operator statement. This statement does the following:

  1. it retrieves the screen’s width;
  2. it compares this width with the maxWidth value from the plugin’s settings, which in our case it’s660px;
  3. if the screen’s width is bigger than 660px, it adjusts the lightbox width to the value of 660px. However, if the screen’s size is smaller than 660px, the lightbox width is resized to the widthstated in the settings, which in this case is 95%.

More on this solution is available on the Colorbox GitHub page.

That’s it for now on the JavaScript front, you’ll come back to it later to deal with WordPress internationalization. Let’s tackle the WordPress side of the project.

Moving on to PHP

At this time, WordPress knows nothing of the presence of jQuery Colorbox in your theme. Neither the plugin’s files nor main.js are being loaded. The recommended practice for loading stylesheets and JavaScript files in WordPress is by using wp_enqueue_style() and wp_enqueue_script() respectively.

Find functions.php in your theme’s files and open it in a code editor. It’s likely your theme already has a function to enqueue style.css. If you can’t find it, adapt the function in the code snippet below to your theme.

[php]
function themeslug_enqueue_styles_scripts() {

//Colorbox stylesheet
wp_enqueue_style( ‘colorbox’, get_template_directory_uri() . ‘/colorbox/colorbox.css’ );

//Your theme CSS
wp_enqueue_style( ‘themeslug-style’, get_stylesheet_uri() );

//Colorbox jQuery plugin js file
wp_enqueue_script( ‘colorbox’, get_template_directory_uri() . ‘/colorbox/jquery.colorbox-min.js’, array( ‘jquery’ ), ”, true );

//Add main.js file
wp_enqueue_script( ‘themeslug-script’, get_template_directory_uri() . ‘/js/main.js’, array( ‘colorbox’ ), ”, true );

}

//Hook the function above
add_action( ‘wp_enqueue_scripts’, ‘themeslug_enqueue_styles_scripts’ );
[/php]

Let’s explain what the code above does.

  • It wraps all the calls to wp_enqueue_style() and wp_enqueue_script() inside a function calledthemeslug_enqueue_styles_scripts().
  • Inside themeslug_enqueue_styles_scripts(), the Colorbox CSS file is enqueued before the theme’s stylesheet.
  • The Colorbox JavaScript file is enqueued pointing to the jQuery library as a dependency, i.e.,jquery.colorbox-min.js loads only after the jQuery library file has already been loaded.
  • The theme’s JavaScript file, main.js, is enqueued next, indicating jquery.colorbox-min.js as a dependency.
  • The argument true at the end of wp_enqueue_script() ensures that the JavaScript files are loaded in the page’s footer area, before the closing </body> tag.
  • Finally, the themeslug_enqueue_styles_scripts() function is hooked into thewp_enqueue_scripts() action. This ensures that stylesheet and script files are loaded at the right time.

If you’re using a child theme, make sure you replace all instances of get_template_directory_uri()with get_stylesheet_directory_uri().

Also, don’t forget to replace all instances of themeslug with your actual theme’s slug.

At this point, your lightbox should be fully functional. However, we’re working with WordPress, and the job is not properly done until the Colorbox plugin’s text strings are translation-ready. Let’s handle this last task.

Internationalizing the JQuery Colorbox Text Strings

It’s recommended that all text strings in a WordPress theme or plugin should be internationalized and is called Internationalization

WordPress uses the gettext libraries for this task. If you’ve worked with WordPress themes or plugins, you’re likely to have come across some of the gettext functions, like __() and _e().

These and other translation functions usually include the text string to be translated as one of their arguments, together with the theme’s or plugin’s textdomain. This is a unique identifier enabling WordPress to distinguish among all the different translations.

jQuery Colorbox has its own text strings. You can find them by opening any of the files in the i18n folder. We need to make sure these strings are somehow sent to WordPress so that they can be internationalized together with your theme’s text strings. The problem is: how do I transfer data from JavaScript code to WordPress?

The answer lies with a great WordPress function called wp_localize_script() .

wp_localize_script() takes three required parameters:

  • $handle. This is the handle or identifier for the script where the text strings are located. The data for this parameter is the first argument in the wp_enqueue_script() function used to enqueue the Colorbox JavaScript file. In this case it’s ‘colorbox‘;
  • $object_name. This is an object created by the wp_localize_script() function, which will be accessible from the JavaScript code in main.js;
  • $l10n. This parameter represents the actual data to be communicated from the JavaScript code to WordPress as an array of key/value pairs.

Let’s see wp_localize_script() in action. Locate the themeslug_enqueue_styles_scripts()function you wrote previously in functions.php. Just below the line of code to enqueue the Colorbox JavaScript file …

[php]
wp_enqueue_script( ‘colorbox’, get_template_directory_uri() .
‘/colorbox/jquery.colorbox-min.js’, array( ‘jquery’ ), ”, true );
[/php]

… add the following code:

[php]
//Make the Colorbox text translation-ready
$current = ‘current’;
$total = ‘total’;
wp_localize_script( ‘colorbox’, ‘themeslug_script_vars’, array(
‘current’ => sprintf(__( ‘image {%1$s} of {%2$s}’, ‘themeslug’), $current, $total ),
‘previous’ => __( ‘previous’, ‘themeslug’ ),
‘next’ => __( ‘next’, ‘themeslug’ ),
‘close’ => __( ‘close’, ‘themeslug’ ),
‘xhrError’ => __( ‘This content failed to load.’, ‘themeslug’ ),
‘imgError’ => __( ‘This image failed to load.’, ‘themeslug’ )
)
);
[/php]

Regular strings in the code above are internationalized using __('string', 'textdomain') function. However, current and total are not being used as simple text strings. In fact, Colorbox uses them as placeholders to workout the number of the current photo and of the total number of photos respectively. To preserve this functionality, the code above uses the PHP sprintf() function with appropriate placeholders.

Next, go back to the Colorbox configuration script in main.js and add this code inside the cbSettingsJavaScript object, after title:

[javascript]
current: themeslug_script_vars.current,
previous: themeslug_script_vars.previous,
next: themeslug_script_vars.next,
close: themeslug_script_vars.close,
xhrError: themeslug_script_vars.xhrError,
imgError: themeslug_script_vars.imgError
[/javascript]

Now the Colorbox configuration settings code looks like this:

[javascript]
//Settings for lightbox
var cbSettings = {
rel: ‘cboxElement’,
width: ‘95%’,
height: ‘auto’,
maxWidth: ‘660’,
maxHeight: ‘auto’,
title: function() {
return $(this).find(‘img’).attr(‘alt’);
},
current: themeslug_script_vars.current,
previous: themeslug_script_vars.previous,
next: themeslug_script_vars.next,
close: themeslug_script_vars.close,
xhrError: themeslug_script_vars.xhrError,
imgError: themeslug_script_vars.imgError
}
[/javascript]

Awesome, you’ve just configured the internationalization settings.

Values in each key/value pair use the themeslug_script_vars object from thewp_localize_script() function you created earlier. It’s this object that makes the JavaScript variable accessible to PHP.

Conclusion

That’s all, the task of adding lightbox functionality to the native WordPress gallery using jQuery Colorbox has been accomplished.

To check the result, add a gallery to a post or page and select the Media File option from the Link toGallery Settings. Now access the gallery from the front-end and click on an image. You should be able to see the image pop up with a sleek lightbox effect.

If you’re not happy with the lightbox’ appearance, you can change the CSS code you find in the Colorbox stylesheet using your theme’s style.css file.

Would you rather have used a WordPress Colorbox plugin or did you enjoy coding up the functionality yourself?

Let me know what you think!

Share Your Thoughts

Copyright © 2011, 2016 - BWD MEDIA
Web Design & Digital Marketing Agency
Call Now Enquire