A few posts ago, I walked through the process of adding custom image attributes to an image in WordPress. I received a good question on Twitter:
I don’t understand the purpose for this though.
— idiot_girl (@idiot_girl) October 24, 2017
So I thought it worth to work through why this may be important or something that’s worthwhile to do (I mean, I don’t know if it’s important, but it could be depending on the project :).
Why Custom Image Attributes Are Useful
Whenever you add custom attributes to images (and I typically think of these as things such as data-type=”acme, “ but they really could be anything like class attributes, IDs, etc. though there are other filters for certain things).
Anyway, adding custom image attributes can add a multitude of abilities that we don’t normally have. Outside of simply making it easier to style images, it also makes it possible for us to use them to access images in a variety of different ways.
That is, we can access them using:
- CSS selectors,
- JavaScript,
- etc.
And when you have access to images outside of the standard WordPress attributes, you’re able to do more with them. Case in point. In short, you’re able to do things like:
- access an image,
- setup event handlers,
- add elements to the DOM,
- setup custom event handlers.
But that’s not all. This is but one example.
Ultimately, one of the primary ideas behind being able to add custom image attributes to WordPress images is that it gives us more control over how we can access our images, work with them, their ancestors, descendants, and more.
But how I use this will likely be different than how you or anyone else will use them. And with that said, I hope this answers why this can be useful.
If not, don’t hesitate to tweet me and I’m happy to share more about it.