WordPressで imgタグから width/height属性を削除する

WordPressでメディアを挿入すると、画像には width属性と height属性が付加されてしまいます。

しかし近年は、レスポンシブ・Webデザインの採用などで幅が画面サイズによって変わるなどで、これらの属性は不要な場合が多々あります。
そこで、これらの属性を削除する方法を探していたら、次のブログで紹介されていました。「image_send_to_editor」や「post_thumbnail_html」のフィルターフックして作ることができるようですね。

add_filter( ‘image_send_to_editor’, ‘remove_image_attribute’, 10 );

add_filter( ‘post_thumbnail_html’, ‘remove_image_attribute’, 10 );

function remove_image_attribute( $html ){

$html = preg_replace( '/(width|height)="\d*"\s/', '', $html );

$html = preg_replace( '/class=[\'"]([^\'"]+)[\'"]/i', '', $html );

$html = preg_replace( '/title=[\'"]([^\'"]+)[\'"]/i', '', $html );

$html = preg_replace( '/<a href=".+">/', '', $html );

$html = preg_replace( '/<\/a>/', '', $html );

return $html;

}

引用元: WordPress:メディア挿入時の不要な属性を削除して、管理画面の「添付ファイルの表示設定」も目隠しする方法 | NxWorld.

コメントを残す