我想为页面上的所有图像(WordPress帖子/页面)添加一个CSS类,它们低于某个宽度。使用DomDocument将一个CSS类添加到页面上宽度小于480像素的所有图像
下面的工作,但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');
2012-08-16
Andrew
+0
Firebug中的宽度是根据浏览器中的实际输出计算出来的,使用php,您需要使用ImageMagick获取每个图像的一个过程,以找出实际宽度。所以最好的方法是使用jQuery或任何其他JavaScript库。 –
2012-08-16 00:45:16
+0
@ThomasStachl谢谢。如果我正确理解了你的话,那么你就说使用PHP来获取图片的真实大小是不可能的。 Bugger,想避免这个jQuery。 –
2012-08-16 00:57:36
+0
@ThomasStachl实际上,现在我想到了,我可能会搜索每个图像的'width'属性,因为每个图像都有一个。反而会给那个镜头。 –
2012-08-16 01:01:48