更新日期:2023-07-31

在編輯器裡面插入圖片,系統會自動幫你寫入寬度和高度標籤,但是如果要做 RWD 效果,這樣子就無法使用了。
像這樣子:
[code]
<img width="300" height="200" src="abcdefg.jpg" class="size-full attachment-post-image wp-post-image">
[/code]

 

所以我們可以用 add_filter 去改變它:
[php]
add_filter( ‘post_thumbnail_html’, ‘remove_attribute’, 10 );
add_filter( ‘image_send_to_editor’, ‘remove_attribute’, 10 );
add_filter( ‘the_content’, ‘remove_attribute’, 10 );

function remove_attribute( $html ) {
$html = preg_replace( ‘/(width|height)="\d*"\s/’, "", $html ) ;
return $html;
}
[/php]

 

但事實上我們也可以利用 css 來改造 img 的寬度就好,css 裡面有一個屬性 max-width (最大寬度)。當你的 img 有 width 和 max-width 屬性時,那規則就要變成這樣子:

  • 當 width < max-width 時,img 的寬度等於屬性 width 的值。
  • 當 width > max-width 時,img 的寬度等於屬性 max-width 的值。

所以我們可以在 css 裡面改寫 img,像這樣子:
[css]
img.size-full{ max-width:100% }
[/css]