wordpressで画像挿入時にimgタグに付くwidthやheightと不要なclassを無くす方法
wordpressで画像挿入をすると、imgタグに「width」や「height」、そして「alignnone」「size-large」などのclassが付与されます。widthやheightはレスポンシブで作るときに邪魔な事があるのと、alignnoneなどのclassは、個人的にあまり使うことはありません。
以前までは手で消してたりしたのですが、毎回手動で消すのも面倒なので、function.phpを編集して、あらかじめこれらの属性やclassを付かないようにしましたので、その方法をご紹介します。
width、heightを付かなくする為に、function.phpに以下を追加します
1 2 3 4 5 6 |
function remove_img_attr($html) { $html = preg_replace('/ (width|height)."\d*"/', '', $html); // width・heightを削除 return $html; } add_filter('get_image_tag', 'remove_img_attr'); |
これにより、width、heightを付かないようにできます。
続いて、不要なclassを削除します
1 2 3 4 5 6 |
function remove_img_attr($html) { $html = preg_replace('/ (width|height)."\d*"/', '', $html); // width・heightを削除 $html = preg_replace('/ class=".+"/', '', $html); // 不要なclassを削除 return $html; } add_filter('get_image_tag', 'remove_img_attr'); |
$html = preg_replace(‘/ class=”.+”/’, ”, $html);
を追記します。これで、classの方も取り去ることが出来ました。
自分で任意のclassを付けたい場合は?
classを消すだけじゃなく、自分で好きなclassを付けたい事もあると思います。その場合にはpreg_replaceの第二引数に自分の付けたいclassを入力します。
例として、「article-image」というclassを付けたい場合、以下のとおりになります。
1 2 3 4 5 6 7 |
function remove_img_attr($html) { $html = preg_replace('/ (width|height)."\d*"/', '', $html); // width・heightを削除 $html = preg_replace('/ class=".+"/', ' class="article-image"', $html); // 不要なclassを削除し、「aritle-image」classを追加 return $html; } add_filter('get_image_tag', 'remove_img_attr'); |
以上を行うことで、かなりタグがスッキリとしました。
以前紹介した、wordpressで画像を挿入する時にメディアファイルに付くリンクをデフォルト「なし」にする方法と併せて使うと、wordpressで画像挿入時に手軽に綺麗なhtmlタグが挿入されるのでオススメです。