This is day 8 of my WordPress Developer Advent Calendar.
If you use WordPress, then at some point you have used the gallery shortcode. It makes it very easy to include a nice looking gallery on a page or post. But I find it has some limitations from a developer point of view. It is not easy to customize the HTML that the gallery shortcode outputs.
I needed a custom class name added to the div element that is output by the gallery shortcode. This is not easy to do, but it is possible. You can simply hook into the post_gallery filter and output your own HTML, but I didn’t want to do that. WordPress does a whole bunch of stuff inside the gallery_shortcode function and I do not want to reinvent the wheel, cause that would mean keeping my code up to date with every new release of WordPress.
I have been thinking about creating my own custom gallery shortcode output for ages now, but it suddenly occurred to me that if I wrap the gallery shortcode with my own shortcode, then I can access the output of the gallery and alter certain things. So I played around with the idea and the Gallery Wrapper plugin was born.
It allows you to customize a few things about the gallery:
- Append your own class to the surrounding div of the gallery.
- Append your own class to each img tag within the gallery.
- Add your own class to each anchor tag within the gallery.
- Add any custom attribute to the surrounding gallery div.
[ gallery-wrap class="cool-gallery" img_class="cool-img" a_class="cool-anchor" data-foo="bar" ] [ gallery link="file" ids="8,9,10,11,5" ] [ /gallery-wrap ]
The above example will result in the following:
- A class name of “cool-gallery” will be added to the surrounding gallery div element.
- A class name of “cool-img” will be added onto each image tag within the gallery.
- A class name of “cool-anchor” will be added onto each anchor tag within the gallery.
- The attribute “data-foo=’bar’” will be added onto the surrounding gallery div element.
A Better Solution
I realize that this might not be everyone’s cup of tea. Some might say “What, another shortcode!” or “why not just extend the gallery shortcode itself”. These are valid comments. This plugin is a quick hack to a silly problem. The ideal solution would be to allow for this customization via gallery-specific filters built into core. We just need someone to submit a patch to allow for that. Actually, that’s a good idea… I think I might do just that! (watch this space)