Filtering the Gallery Image Output in WordPress – Adding Class or Data Attribute

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.

wordpress-gallery-output-link

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.

data-gall='gallery-{$instance}'

or

class='gallery-class-{$instance}'

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!

 

Leave a Comment





%d bloggers like this: