How to Apply Links to WordPress Native Gallery Captions

The WordPress native gallery is very easy to use and this functionality helps us build beautiful layouts, directly from the pages and posts content.

Most of the times, when using the native gallery feature, I add a caption to the images I display, and the majority of layouts display the caption as a simple overlay on top or under the image. When clicking the overlay, which is the most intuitive way to open the image in a lightbox or to get to a page with details, it is not working, as the caption is not included in the clickable element, but just applied on top of it, hence, clicking on it will do nothing.

I came up with a fix for this in my projects, which consists of two small pieces of code that are fixing this, one for the non-Gutenberg (as a filter) and the other one for the Gutenberg gallery block (as a small javascript).

See below an example of how the link to the media should be available for the whole gallery element, including the caption, when you move over the image. Do not mind the styling, it’s just for demo purposes.


For non-Gutenberg use, we can use the native hooks to override the gallery output to what we need:

add_filter( 'post_gallery', 'replace_post_gallery_output', 10, 3 );

/**
 * Replace post gallery output.
 *
 * @param string  $output   The gallery output. Default empty.
 * @param array   $atts     Attributes of the gallery shortcode.
 * @param integer $instance Unique numeric ID of this gallery shortcode instance.
 * @return string
 */
function replace_post_gallery_output( $output = '', $atts = null, $instance = null ) {
	... // Add custom code here.
}

For Gutenberg gallery block:

(function($) {
	$(document).ready(function() {
		var $itemsLinks = $('.blocks-gallery-item figure a');
		if ($itemsLinks.length) {
			$itemsLinks.each(function() {
				var $sib = $(this).siblings('figcaption');
				if ($sib.length) {
					$sib.detach();
					$(this).append($sib);
				}
			});
		}
	});
})(jQuery);

Here is the entire code, merged into a single plugin that will handle both use-cases. You can download, install and activate the plugin on your site, no need to make any extra settings. Here you can download the WordPress plugin. Please note that this is working for the native gallery feature, and it has been tested with WordPress 5.2.


See other plugins