
[WordPress] アイキャッチで出力される img タグ中のサイズやクラスを変更したり削除したりする
<?php the_post_thumbnail(); ?>タグでアイキャッチ画像を表示すると以下のような形で img タグがHTMLに出力されます。
この img タグ内の width/height 指定やクラス名を任意のものへ変更したり、削除する方法のメモです。
img タグ内のサイズ指定を変更する
the_post_thumbnail() に以下のように array( 橫, 縦 ) に表示したいサイズを渡します。
<?php the_post_thumbnail( array(200, 200) ); ?>
これで以下のように img タグが変更されます。
独自のクラスを付ける
the_post_thumbnail() タグの第二引数に以下のように任意のクラス(myClass の部分)を入れます。
<?php the_post_thumbnail( 'thumbnail', array('class' => 'myClass') ); ?>
クラス名が変更されました。
もっと独自のクラスにする
wp-post-image というクラス名は表示されている画像のサイズによって自動的に付けられます。例えば thumbnail サイズが表示されている場合は attachment-thumbnail というクラス名が付きます。
これにより実際の表示サイズが確認できるので便利ですが、これを削除して独自クラス名のみにしたいという場合は functions.php へ以下のように記入します。
add_filter( 'post_thumbnail_html', 'custom_attribute' ); function custom_attribute( $html ){ $myclass = 'myclass'; // クラス名 return preg_replace('/class=".*\w+"/', 'class="'. $myclass .'"', $html); }
post_thumbnail_html フィルターフックを使うと、custom_attribute の第一引数でアイキャッチのHTMLを文字列で受け取ることができるので、受け取ったimgタグの文字列から preg_replace() を使ってクラス名を変更します。
↓ 変更後の HTML
クラス名を削除する
クラス指定そのものを削除する場合は functions.php へ以下のように記入します。
add_filter( 'post_thumbnail_html', 'custom_attribute' ); function custom_attribute( $html ){ // class を削除する $html = preg_replace('/class=".*\w+"\s/', '', $html); return $html; }
↓ 変更後の HTML
サイズ指定を削除する
img タグへサイズ指定を入れたくない場合は functions.php へ以下を記入します。
add_filter( 'post_thumbnail_html', 'custom_attribute' ); function custom_attribute( $html ){ // width height を削除する $html = preg_replace('/(width|height)="\d*"\s/', '', $html); return $html; }
↓ 変更後の HTML
テンプレートタグ/the post thumbnail – WordPress Codex 日本語版
WordPressで画像挿入時にwidthとheightを削除する方法 | Web活メモ帳
2 Comments & Tracbacks