WordPressの記事で<figure>
タグを使うと、自動整形でマークアップがおかしくなることがあります。
例えばこんな風に書いた場合。
<figure>
<img src="hoge.png" alt="fuga" />
<figcaption>Caption</figcaption>
</figure>
仕様書の例にも載っているfigure
要素の基本的な使い方ですね。
これが自動整形によって、
<figure> <img src="hoge.png" alt="fuga" /></p> <figcaption>Caption</figcaption> </figure>
<img>
の後ろに余計な</p>
が付与されてしまいます。
<figcaption>
タグを先に書いた場合は、
<figure> <figcaption>Caption</figcaption> <p><img src="hoge.png" alt="fuga" /><br /> </figure>
のように、<p>
と<br />
が付いてきます。
実はこれは<figure>
タグに限った話ではなくて、"ブロックレベル"的要素と"インライン"的要素を並べて書くと起こりうる問題です。
figure
要素は特にfigcaption
との兼ね合いから、問題が起こりやすいと思うので、これを修正するためのコードを作りました。
function fix_autop_figure1($content) {
$content = preg_replace('!(<figure[^>]*>)\s*!', '$1', $content);
$content = preg_replace('!\s*</figure>!', '</figure>', $content);
$content = preg_replace('!</figcaption>\s*!', '</figcaption>', $content);
$content = preg_replace('!\s*(<figcaption[^>]*>)!', '$1', $content);
return $content;
}
function fix_autop_figure2($content) {
$content = preg_replace('!<br />\s*(?=<figcaption[^>]*>)!', "\n", $content);
$content = preg_replace('!^<p>(.+?)</figure>$!m', '$1</figure>', $content);
$content = preg_replace('|(<figure[^>]*>)(?!\n)|', "$1\n", $content);
$content = preg_replace('|(?<!\n)</figure>|', "\n</figure>", $content);
return $content;
}
add_filter('the_content', 'fix_autop_figure1', 9);
add_filter('the_content', 'fix_autop_figure2', 11);
これをfunctions.phpに追加します。
まず一つ目の関数で、figure
の開始タグ後と終了タグ前、figcaption
の開始タグ前と終了タグ後の空白文字を全て削除しています。これで余計な</p>
タグの挿入を防ぎます。wpautop
フィルタより先に実行するために、プライオリティーを9としています。
二つ目の関数はwpautop
フィルタ実行後に、余計な<p>
と<br />
を削除するものです。後ろ二つのpreg_replace
はソースを見やすくするために改行を入れるだけなので、削っても問題ありません。
これでよほど変な書き方しない限り、おかしなマークアップにはならないと思います。
wpautop
を切っちゃうのが一番早いんですけどね。
Comments