Dodaj klasę CSS do wszystkich obrazów na stronie, które mają szerokość mniejszą niż 480px za pomocą DomDocument

Chciałbym dodać klasę CSS do wszystkich obrazów na stronie (post / strony WordPress), które są poniżej pewnej szerokości.

Poniższe działa, alesetAttribute zastępuje wszystkie nazwy klas w każdym img nowym.

Jak mogę dodać nową klasę do każdego obrazu bez zastępowania istniejących klas?

function add_class_to_small_images( $content ) {

$dom = new DOMDocument();
@$dom->loadHTML( $content );
$dom->preserveWhiteSpace = false;

$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {

    $width = $image->getAttribute('width');

    if( $width < 480) {
        $image->setAttribute('class', 'this-will-be-the-class'); // the new class
    }
}

  $content = $dom->saveHTML();


return $content;
}
add_filter('the_content', 'add_class_to_small_images');

questionAnswers(1)

yourAnswerToTheQuestion