0

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();
    libxml_use_internal_errors(true);
    $document->loadHTML(utf8_decode($content));

    $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('src','');
        $img->setAttribute('srcset','');

        $img->setAttribute('class',$existing_class . ' js-lazy-image');
        $img->setAttribute('data-src',$orig_src);
        $img->setAttribute('data-srcset',$orig_srcset);
    }

    $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!

9
  • By page, do you mean the page post type, or simply other pages like homepage or archives?
    – Johansson
    Commented Aug 22, 2017 at 22:09
  • Is the utf8_decode necessary?
    – Tom J Nowell
    Commented Aug 22, 2017 at 22:15
  • What about these hooks? wordpress.stackexchange.com/a/211376/126253 I think you don't need strip attributes manually Commented Aug 22, 2017 at 22:18
  • do those pages have content? if not, you can just add a check if(empty($content)) return $content;
    – inarilo
    Commented Aug 22, 2017 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
    Commented Aug 22, 2017 at 22:21

2 Answers 2

0

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
}
0

For me works great with:

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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