On Lightbox and issues with no-image files


I’ve been running into some troubles while implementing Lightbox on a site (Berlin theme), because of the problem pointed out by @jflatnes in

After some attempts, I might have found a clean solution; here it is, for those who might need it.

  1. First, I declare a custom function:
function addLightbox($item_image_gallery, $filter = array()) 
	if ($item_image_gallery == '' || empty($filter)) return $item_image_gallery;
	// extracts all hrefs and edit them if needed
	$pattern = '~(<a(.*?)(href=[\'"]([^\'"]+)[\'"])(.*?)>)~';
	return preg_replace_callback(
		function ($matches) use ($filter) {
			// searches for extension in href's url
			$url_chunks = explode('.', $matches[3]);
			if (count($url_chunks) > 0) {
				// retrieves file extension, trimming it up
				$file_extension = substr(strtolower($url_chunks[count($url_chunks) -1]), 0, -1);
				// checks whether file extension is in filter array
				if (in_array($file_extension, $filter)) {
					return '<a ' . $matches[3] . ' data-lightbox="lightbox">';
				} else {
					return $matches[1];
			} else {
				return $matches[1];
  1. Then, I pass item_image_gallery as first parameter to addLightbox custom function, the second parameter being the array of extensions accepted:

echo addLightbox(item_image_gallery(), array('jpeg', 'jpg', 'gif', 'png'));

Please note: the function does not check whether there’s any other content in the anchor tag, but it works if needed only for applying Lightbox feature.

Hope this helps.