使用DomDocument将CSS类添加到页面上宽度小于480px的所有图像上 [英] Add a CSS class to all images on a page that have a width less than 480px using DomDocument

查看:93
本文介绍了使用DomDocument将CSS类添加到页面上宽度小于480px的所有图像上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为页面(WordPress帖子/页面)上小于一定宽度的所有图像添加CSS类。

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

以下方法有效,但 setAttribute 正在用新的img替换每个img中的所有类名。

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


推荐答案

好的。抓取现有的类,并将它们添加到带有我想要的新类的setAttribute中。如果有人有更好的方法,请告诉我。

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

这篇关于使用DomDocument将CSS类添加到页面上宽度小于480px的所有图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆