JetPack Tiled Galleries

This slideshow requires JavaScript.


Followed by a thumbnail grid gallery

Add a Data Attribute to a WordPress Gallery via PHP

To manipulate the linked images, specifically the links themselves in the WordPress Gallery output for doing things like adding in a CSS class or a data attribute value you can use the post_gallery filter in /wp-includes/media.php which is the right tool for the job.


The filter can be applied like so…

So this is an exact copy of the original with nothing actually changed in the filter at this point, you can change what you like to suit your needs, the highlighted line is what controls the link around the image and is not easily manipulated.

So instead of using wp_get_attachment_link as the $image_output, you can build the HTML link and use wp_attachment_url as the href value for the clicked image and then use wp_get_attachment_image for the actual image it is surrounding.

So this would be our new $image_output

$image_output = "<a href='" . wp_get_attachment_url( $id ) . "'> " . wp_get_attachment_image($id, $atts['size'], false, $attr ) . "</a>";
$image_output = "<a href='" . wp_get_attachment_url( $id ) . "'> " . wp_get_attachment_image($id, $atts['size'], false, $attr ) . "</a>";
view raw image-output.php hosted with ❤ by GitHub

Adding a Class or Data Attribute

Now that the html is editable you can easily add a class or data attribute.

Say if you wanted a unique class or data attribute for each gallery (if more than one appeared on the page) you can take advantage of the $instance parameter which is a unique ID of each gallery, which you could append to your class to data attribute value.




So if more than one gallery existed on the page they would have these values incremented by 1.

$image_output = "<a href='" . wp_get_attachment_url( $id ) . "' data-gall='gallery-{$instance}'> " . wp_get_attachment_image($id, $atts['size'], false, $attr ) . "</a>";

That’s it, manipulate away!


Add a Data Attribute to a WordPress Gallery via jQuery

You can add a data attribute and value to a WordPress gallery via jQuery


$('#gallery-1 a').each(function() {
 $(this).attr('data-gall', 'gallery-mine' );


So above we are targetting the a link tags that are the descendants of the gallery with an id of #gallery-1

They are then given a data attribute of data-gall and a value of gallery-mine.