
Photo Bench Accounting via Unsplash
WordPressで画像にキャプションを設定すると、次のように横幅を指定したHTMLが出力されます。
<div id="attachment_○○○" class="wp-caption alignnone" style="width: ○○○px"> <img class="size-large wp-image-○○○" src="○○○.jpg" alt="○○○" width="○○○" height="485" <p class="wp-caption-text">キャプション</p> </div>
<div>タグにstyle="width: ○○○px"が指定されています。
このwidthは「画像の幅+10px」で出力されます。そのため、テーマの作りやスタイルがキャプションを想定していないと、スマートフォンで見たときなどに画像が横に大きくはみ出てしまうことがあります。
<div>タグに出力されるwitdhスタイルを削除するには、functions.phpに次のコードを追記します。
//画像キャプションで出力される不要なwidthスタイルを削除
function my_img_caption_shortcode($attr, $content = null) {
if ( ! isset( $attr['caption'] ) ) {
if ( preg_match( '#((?:<a [^>]+>s*)?<img [^>]+>(?:s*</a>)?)(.*)#is', $content, $matches ) ) {
$content = $matches[1];
$attr['caption'] = trim( $matches[2] );
}
}
$output = apply_filters('img_caption_shortcode', '', $attr, $content);
if ( $output != '' )
return $output;
extract(shortcode_atts(array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
), $attr, 'caption'));
if ( 1 > (int) $width || empty($caption) )
return $content;
if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '">' . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}
add_shortcode('caption', 'my_img_caption_shortcode');
これで、WordPressの画像にキャプションを設定したときに画像の横幅がおかしくなる件を解決することができます。