Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/00-the-content.php Secret
Last active Sep 5, 2019

What would you like to do?
[WordPress] Adding Custom WordPress Image Attributes
private function addImageAttributes($content)
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new \DOMDocument();
$images = $document->getElementsByTagName('img');
foreach ($images as $image) {
$image->setAttribute('data-example', 'true');
return $document->saveHTML();

This comment has been minimized.

Copy link

commented Sep 5, 2019

do I just throw this into the functions.php file of my child theme and edit to match the attributes I want to add?


This comment has been minimized.

Copy link
Owner Author

commented Sep 5, 2019

This isn't really designed to be used in a child theme - instead, it's meant for an object-oriented plugin so you'd have to refactor it a bit if you wanted it to work in the context of a theme.

Namely, you'd need to:

  • remove private function the function
  • pass the value of the string or the content into the function that you want it to parse
  • make sure DOMDocument is available in your installation of PHP
  • then echo the code that's returned from this function

It's a lot looking at this way but hopefully it gives you a starting point!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.