wordpressの記事を出力前に正規表現などで記事内容を変更する方法(不要な文字列を削除したり、追加で文字を足したり)

wordpressの記事を出力前に正規表現などで記事内容を変更する方法はthe_contentをfunctions.phpでカスタマイズする

記事中の不要な文字列を削除したり、追加で文字を足したりすることができる

functions.php

function replacement_content($content){

//lightboxのタグを速報に追加
$class_name1 = '<a href="';
$class_name2 = '" data-fancybox data-caption="">';
$pattern = "/(<h3>.*)(<img.*src=\"(https:\/\/xxxxx.com\/wp-content\/uploads\/[0-9]{4}\/[0-9]{2}\/.*png).*\>)/s";
$content = preg_replace($pattern, "$1".$class_name1."$3.png".$class_name2."$2".'</a>', $content);



return $content;
}
add_filter('the_content', 'replacement_content');

上記例では、本文中の画像にlightbox(fancybox3)用のaタグを自動挿入している

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です