Добавьте класс CSS ко всем изображениям на странице с шириной менее 480 пикселей с помощью DomDocument

Я хотел бы добавить класс CSS ко всем изображениям на странице (WordPress post / pages), которые ниже определенной ширины.

Следующие работы, но setAttribute заменяет все имена классов в каждом img новым.

Как добавить новый класс к каждому изображению без замены существующих классов?

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

Хорошо, это работает. Схватил существующие классы и добавил их обратно в setAttribute с новым классом, который я хотел. Если у кого-то был лучший метод, пожалуйста, дайте мне знать.

 function add_class_to_small_images( $content ) { $dom = new DOMDocument(); @$dom->loadHTML( $content ); $dom->preserveWhiteSpace = false; $images = $dom->getElementsByTagName('img'); foreach ($images as $image) { // get the widths of each image $width = $image->getAttribute('width'); // the existing classes already on the images $existing_classes = $image->getAttribute('class'); // the class we're adding $new_class = ' this-will-be-the-class'; // the existing classes plus the new class $class_names_to_add = $existing_classes . $new_class; // if image is less than 480px, add their old classes back in plus our new class if( $width < 480) { $image->setAttribute('class', $class_names_to_add); } } $content = $dom->saveHTML(); return $content; }