简体   繁体   中英

Add a CSS class to all images on a page that have a width less than 480px using DomDocument

I would like to add a CSS class to all images on the page (WordPress post/pages) that are below a certain width.

The following works but setAttribute is replacing all the class names in each img with the new one.

How can I add a new class to each image, without replacing the existing classes?

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

Ok this works. Grabbed the existing classes and added them back into the setAttribute with the new class I wanted. If anyone had a better method, please let me know.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM