Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
[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

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?

@tommcfarlin

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.