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.
Classic Editor Gallery
Most of the time, 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 classic editor
/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);
Download the WordPress Plugin
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.
You can download the file from the link or by clicking the download icon.
Please note that this is working for the native gallery feature, and it has been tested with WordPress 5.2
Click the heart.
Are you interested in more programming tips and tricks?
How to fix translation in multi-language website + WooCommerce + AJAX checkout
I have been working recently on a multi-language…
How to Integrate Google reCAPTCHA v3 in Forms that Use AJAX Validation
I recently had to update one of the sites that is…
Images Optimization for WordPress and Why Just Compressing Images Is Not Enough
Images optimization is a fascinating topic…
How to Setup a Local Development Environment in 5 Minutes
When you are working on diverse projects on your own or with other…