Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active August 18, 2022 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/52ba9093940abf03519d77cd17dfa257 to your computer and use it in GitHub Desktop.
Save tommcfarlin/52ba9093940abf03519d77cd17dfa257 to your computer and use it in GitHub Desktop.
[WordPress] Adding Custom WordPress Image Attributes
<?php
private function addImageAttributes($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new \DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$images = $document->getElementsByTagName('img');
foreach ($images as $image) {
$image->setAttribute('data-example', 'true');
}
return $document->saveHTML();
}
@welbinator
Copy link

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

@tommcfarlin
Copy link
Author

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