-
-
Save tommcfarlin/52ba9093940abf03519d77cd17dfa257 to your computer and use it in GitHub Desktop.
[WordPress] Adding Custom WordPress Image Attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
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
do I just throw this into the functions.php file of my child theme and edit to match the attributes I want to add?