When it comes to working with the_content, it’s straightforward.
- Set up a filter that’s hooked into the_content,
- define a function that accepts the incoming post content,
- make your changes,
- return the modified content.
And most of the time, this is all that’s needed. But there are times in which you may want to do more advanced things.
For example, perhaps you’ll want to include content from an external template. Or maybe you’ll want to add attributes to images that you find in the post.
Custom WordPress Image Attributes
It can be hard to do this using a regular expression (because HTML is a non-regular language) but with the help of PHP’s DOMDocument, it’s not too bad.
The idea behind that code that I’m about to show is as follows:
- look for img tags in the post,
- loop through whatever is found,
- add the attributes,
- save the HTML,
- return the result.
Note that you may need to adjust this based on your own needs, but the basic code that you’ll need is:
For those who are unfamiliar with DOMDocument and what’s happening the in the code above (as in why certain functions are called before processing the markup), here’s a quick rundown:
- mb_convert_encode.This will take the character encoding of the incoming data and convert it into UTF-8 (based on the code above, but it can be something different).
- libxml_use_internal_errors. This will turn off any error reporting and all us, as the programmer, the retrieve the errors on our own.
- utf8_decode. This decodes the information in a string from UTF-8 to ISO-8859-1. The reason we do this is that most pages will have a character set defined as the latter and we need it coded to the former to process it.
That said, I also recommend reading up on DOMDocument for more information about everything that’s happening above.
Nonetheless, once you use the function like what’s above, you’ll have a custom data-example attribute with a value of true on the images throughout your post.