When it comes to working with the_content, it’s straightforward.

  1. Set up a filter that’s hooked into the_content,
  2. define a function that accepts the incoming post content,
  3. make your changes,
  4. 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.

Custom WordPress Image Attributes with DOMDocument

The idea behind that code that I’m about to show is as follows:

  1. look for img tags in the post,
  2. loop through whatever is found,
  3. add the attributes,
  4. save the HTML,
  5. 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.

Category:
Articles
Tags: