_Now a WordPress Plugin, see the most recent version releses: Category > add-rel-lightbox


I really like the pop-up display style of lightbox and slimbox, and WordPress has a really nice integration for adding pictures, but the two don’t talk to each other automatically. Getting images insterted from the WordPress media dialogue has a few requirements:

  • Automatically add the rel="lightbox" to a link that wraps an image, but only when the link points to the original image

  • Be able to identify that the inserted image and link is the format inserted from the WordPress media library

  • Add a caption to the lightbox that is correctly formatted to include any html characters. If you have to manually enter lightbox captions for the same picture on every page, then that’s much worse than only entering them once in the media library

  • should fail gracefully if lightbox or slimbox is removed/deactivated

  • Ignore link-wrapped-images that already have lighbox attributes set

What I’ve got in the form of a basic plugin is shown below.

When a page is loaded, the content is checked for standard link-wrapped-images that are produced from the “Add an Image” tool where they are linked to an original image. Where there is a match, the image caption is retrieved from the database, html characters are escaped and the rel=”lighbox” and caption are added to the link.

<code style="overflow:auto; max-width:91%;" class="block"><?php
/*
Plugin Name: add_rel_lightbox
Description: Add rel="lightbox[this_page]" to &lt;a&gt; wrapped image links in the content, and include captions for lightbox/slimbox
Version: 0.1
Author: Patrick Fenner (Def-Proc.co.uk)
Author URI: http://www.deferredprocrastination.co.uk/
*/

function add_rel_lightbox($content)
{

	/* Find internal links */

	//Check the page for link images direct to image (no trailing attributes)
	$string = '/<a href="(.*?).(jpg|jpeg|png|gif|bmp|ico)"><img(.*?)class="(.*?)wp-image-(.*?)" \/><\/a>/i';
	preg_match_all( $string, $content, $matches, PREG_SET_ORDER);

	//Check which attachment is referenced
	foreach ($matches as $val) 
	{
		$slimbox_caption = '';
		
		$post = get_post($val[5]);
		$slimbox_caption = esc_attr( $post->post_content );
		
		//Replace the instance with the lightbox and title(caption) references. Won't fail if caption is empty.
		$string = '<a href="' . $val[1] . '.' . $val[2] . '"><img' . $val[3] . 'class="' . $val[4] . 'wp-image-' . $val[5] . '" /></a>';
		$replace = '<a href="' . $val[1] . '.' . $val[2] . '" rel="lightbox[this_page]" title="' . $slimbox_caption . '"><img' . $val[3] . 'class="' . $val[4] . 'wp-image-' . $val[5] . '" /></a>';
		$content = str_replace( $string, $replace, $content);
	}

	return $content;
}

/* Filter Hook */

add_filter('the_content', 'add_rel_lightbox', 2);

?>
</code>

_Now a WordPress Plugin, see the most recent version releses: Category > add-rel-lightbox