1

我想为页面上所有低于特定宽度的图像(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');
4

1 回答 1

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;
}
于 2012-08-16T02:52:55.610 回答