I have a function like this :

function add_responsive_class($content)
    $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
    if (!empty($content)) {
        $document = new DOMDocument();

        $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');

this adds img-fluid to all the images but also it removes the align-left , how can i modify the above function to add img-fluid to image instead of it removing the other classes?

like --> <img class ="img-fluid align-left"

$img->setAttribute('class', 'img-fluid');

This sets the class field to a new value. Simply change this line to

$classes = $img->getAttribute('class');
$img->setAttribute('class', $classes . ' img-fluid');

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.