我想为页面上的所有图片(WordPress帖子/页面)添加一个CSS类,这些图片的宽度低于一定宽度。
以下有效,但 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');
答案 0 :(得分:3)
好的,这有效。抓住现有的类并使用我想要的新类将它们添加回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;
}