ブログ

BLOG

[WordPress] 画像のキャプションで横幅が10px増えているのを消す方法

[WordPress] 画像のキャプションで横幅が10px増えているのを消す方法

WordPressで画像にキャプションを設定して、メディアから追加すると何故か10px増えている。んです。
なんやこの機能は、、ということでこの10pxを追加しないような処理を行おうと思います。

10pxの現象

「メディアから追加」から追加するとキャプションがあった場合、このように表示されると思います。

[caption id="attachment_{post id}" align="alignnone" width="2000"]<img class="size-full wp-image-{post id}" src="{画像のパス}" alt="" width="2000" height="1500" /> キャプション内容[/caption]

koukiTipsの場合は、現在横幅800pxで設定しているので、例えば800pxに設定して書くじゃないですか〜?

[caption id="attachment_{post id}" align="alignnone" width="800"]<img class="size-full wp-image-{post id}" src="{画像のパス}" alt="" width="2000" height="1500" /> キャプション内容[/caption]

で、ブラウザで見ると、インラインでstyle=”width: 810px”ってなっちゃうんですよ。

<div id="attachment_{id}" style="width: 810px" class="wp-caption alignnone">
  <img src="パス">
  <p class="wp-caption-text"><a href="パス" target="_blank" rel="noopener noreferrer">キャプション</p>
</div>

困る。

ということで解決策。

10px増えないようにする

functions.phpに下記のコードを書きます。

webpack.config.js

function remove_caption_padding( $width, $atts, $content ) {
    $width = $width - 10; // ここで10px引く
    return $width;
}
add_filter( 'img_caption_shortcode_width', 'remove_caption_padding', 10, 3 );

とりあえずはこれで、解決するはず!

が!!

毎回、captionのショートコードにwidht設定めんどくさい。。

ということで、インラインのstyleは消しちゃおう♪
ということで最終的なコードは下記になります!

webpack.config.js

add_filter('img_caption_shortcode', 'my_img_caption_shortcode_filter',10,3);
function my_img_caption_shortcode_filter($val, $attr, $content = null)
{
    extract(shortcode_atts(array(
        'id'    => '',
        'align' => '',
        'width' => '',
        'caption' => ''
    ), $attr));

    if ( 1 > (int) $width || empty($caption) )
        return $val;

    $capid = '';
    if ( $id ) {
        $id = esc_attr($id);
        $capid = 'id="figcaption_'. $id . '" ';
        $id = 'id="' . $id . '" aria-labelledby="figcaption_' . $id . '" ';
    }

    return '<figure ' . $id . 'class="wp-caption ' . esc_attr($align) . '" >'
    . do_shortcode( $content ) . '<figcaption ' . $capid 
    . 'class="wp-caption-text">' . $caption . '</figcaption></figure>';
}

もし独自で編集したかったら、最後の行あたりのreturnのところをごにょごにょしてください!

ということで、設定完了!!

お問い合わせ・ご相談CONTACT

オクワスでは、Webを通して魅力を最大限に伝えるお手伝いをしております。ホームページ制作やWebからの集客などでのお困りごと、Web開発で人手が足りないなどございましたら一度お気軽にご連絡ください。

お問い合わせフォームまたは𝕏のDMからご相談お受けしております。

お問い合わせフォームへDMからご連絡ください
© 2015 - 2024 Okuda Kouki