WordPress記事内の画像をdivタグで囲う方法

PHPの正規表現を利用して、投稿記事の画像を<div>タグで囲う方法の備忘録です。

通常、WordPressのエディタで「画像」を使用すると、ページ上では下記のような<figure>タグで囲まれた<img>タグで表示されます。

<figure class="wp-block-image size-full">
  <img decoding="async" width="800" height="800" src="sample.png" alt="" class="wp-image-2595" srcset="">
</figure>

画像を表示する部分を<div>タグで囲うように、functions.phpにコードを記述します。

function image_wrap_div($content){
  $pattern = '/<figure(.*?)<\/figure>/s';
  $replace = '<div><figure$1</figure></div>';
  $content = preg_replace($pattern, $replace, $content);
  return $content;
}
add_action('the_content', 'image_wrap_div');

正規表現を使用して、「<figure」から「</figure>」間の値を「<div><figure」と「</figure></div>」で挟むようにpreg_replace()で置換しています。

改行が含まれていてもマッチできるように、$patternの最後にパターン修飾子sを使っています。

エラーがなければ、下記のようなコードで出力されます。

<div>
  <figure class="wp-block-image size-full">
    <img decoding="async" width="800" height="800" src="sample.png" alt="" class="wp-image-2595" srcset="">
  </figure>
</div>
Share on Twitter
関連記事
PHPで「in_array() expects parameter 2 to be array…」エラーが表示された時の対処法
PHPで「in_array() expects parameter 2 to be array…」エラーが表示された時の対処法
サクラエディタでPHPの文字色を変更する方法
サクラエディタでPHPの文字色を変更する方法
WordPressにslickでスライドショーを実装する方法
WordPressにslickでスライドショーを実装する方法