0

I am working in WordPress and added some code in my functions.php that will prevent WordPress from adding default classes to the image and add my own class. This works except now when I create a new post it gives me an error (see screenshot). If I remove the lines of code it removes the error but I'd like to keep the code as I need the function for my website.

I looked this error up even though I don't understand what in my code is causing it and someone on another Stackoverflow suggested adding this code for a similar error:

libxml_use_internal_errors(false);

I added this and it did not work, since I did not fully understand it I have removed it for now pending help from this question. I appreciate any help!

functions.php

function add_responsive_class($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) {
           $img->setAttribute('class','img-fluid');
        }

        $html = $document->saveHTML();
        return $html;
}

add_filter('the_content', 'add_responsive_class');

// disable srcset on frontend
add_filter('max_srcset_image_width', create_function('', 'return 1;'));

Screenshot of error

user5854648
  • 1,029
  • 2
  • 11
  • 36
  • What is the content from `utf8_decode($content)` ? Does this look like your soruce HTML? Do you actually need `mb_convert_encoding()` / `utf8_decode()`? – Scuzzy Dec 17 '18 at 01:29
  • Do you only need this class for styling purposes, or for other stuff (like selecting elements in scripts) as well? Because if it is the former, I’d rather apply the styles in question to all `img` elements via the stylesheet, instead of giving every single image that same class … – misorude Dec 17 '18 at 09:04

1 Answers1

0

I resolved this by removing the code from functions.php. I took a user suggestion and styled image tags with CSS, the better solution.

user5854648
  • 1,029
  • 2
  • 11
  • 36