I'm trying to modify the Image Output on my Wordpress-Site to replace src and srcset with their "data-" Equivalent while adding an additional class. Therefor I'm using DOMDocument and filter for imgs. Here's my code:

function image_manipulation( $content ) {

    $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
    $document = new DOMDocument();

    $imgs = $document->getElementsByTagName('img');
    foreach ($imgs as $img) {
        $orig_src = $img->getAttribute('src');
        $orig_srcset = $img->getAttribute('srcset');
        $existing_class = $img->getAttribute('class');


        $img->setAttribute('class',$existing_class . ' js-lazy-image');

    $html = $document->saveHTML();
    return $html;
add_filter ('the_content', 'image_manipulation');

Everything works on posts, but if I open any page, I get an error saying "Warning: DOMDocument::loadHTML(): Empty string supplied as input in functions.php on line 73" (line 73 is the line with loadHTML in it).

I'm stucked... Thanks for any good hints in advance!

  • By page, do you mean the page post type, or simply other pages like homepage or archives? – Jack Johansson Aug 22 '17 at 22:09
  • Is the utf8_decode necessary? – Tom J Nowell Aug 22 '17 at 22:15
  • What about these hooks? wordpress.stackexchange.com/a/211376/126253 I think you don't need strip attributes manually – Anton Lukin Aug 22 '17 at 22:18
  • do those pages have content? if not, you can just add a check if(empty($content)) return $content; – inarilo Aug 22 '17 at 22:21
  • @jack-johansson I mean the page post type, like my normal "about" page. The error doesn't occure on archive pages btw. @tom-j-nowell It isn't necessarly, but the error remains the same if I delete this part... – Dennis Aug 22 '17 at 22:21

If the pages that are giving errors have no content, you can deal with it by adding a check at the start of the function:

function image_manipulation( $content ) {
  if(empty($content)) return $content;
  //rest of the code
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.