I ran into a problem recently. I wanted to have links to images be “lightboxed,” but I also wanted to blog in Markdown and not have to write out link tags with “rel” attributes for every image link. There are several existing plugins for Wordpress that will do this automatically, but I’ve been sticking with the jQuery Lightbox plugin, which handles Wordpress galleries in this manner, but requires the “rel=lightbox” attribute to handle single image links.
I’m not a big fan of directly modifying plugins, primarily because it means that my changes will be scrapped if I ever automatically update the plugin. Since all I’m doing is adding a little jQuery to apply the effect to some additional selectors, I’ve just added it into an external Javascript file that I was already loading. Here’s what I did…
The extra jQuery to run the lightbox effect on every link whose target ends with “jpg” is very simple:
// Auto-handle direct jpeg links
$('a[href$="jpg"]').not('.gallery a').each(function() {
$(this).lightbox();
});
It selects any link whose href value ends with ‘jpg’. I added a .not()
selector to exclude the Wordpress gallery links that the plugin already does a nice job of handling and turning into navigable lightbox galleries. This little bit of code will work with any flavor of the jQuery Lightbox plugin that uses “lightbox()” as its main function. Next I put this snippet into my js file, in the function that executes when the document is ready:
jQuery(document).ready(function($) {
// Auto-handle direct jpeg links
$('a[href$="jpg"]').not('.gallery a').each(function() {
$(this).lightbox();
});
});
The “$” inside of the function’s parameters (function($)
) lets us use the standard jQuery “$” inside of the function, instead of the no-conflict “jQuery.” Just a convenience, but if you don’t do this, and you have the default jQuery library loaded in Wordpress, you’ll need to replace all of the “$” in the original snippet with “jQuery” to get it to work.
I add the external javascript to the queue in my theme’s functions.php file like this:
function bt_load_scripts() {
wp_enqueue_script('brettterpstra',TEMPLATEPATH.'/js/brettterpstra.js',array('jquery'),false,true);
}
if (!is_admin()) {
add_action('init', bt_load_scripts);
}
That did the trick, and any JPEG image I link to directly now gets the lightbox treatment. I haven’t run into any conflicts yet, but I’ll keep my eyes peeled and refine the selector if I need to.