2012-08-16 60 views
1

我想爲頁面上的所有圖像(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'); 
+0

Firebug中的寬度是根據瀏覽器中的實際輸出計算出來的,使用php,您需要使用ImageMagick獲取每個圖像的一個過程,以找出實際寬度。所以最好的方法是使用jQuery或任何其他JavaScript庫。 – 2012-08-16 00:45:16

+0

@ThomasStachl謝謝。如果我正確理解了你的話,那麼你就說使用PHP來獲取圖片的真實大小是不可能的。 Bugger,想避免這個jQuery。 – Andrew 2012-08-16 00:57:36

+0

@ThomasStachl實際上,現在我想到了,我可能會搜索每個圖像的'width'屬性,因爲每個圖像都有一個。反而會給那個鏡頭。 – Andrew 2012-08-16 01:01:48

回答

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; 
} 
相關問題