概要説明
広告の挿入などでよく使われるカスタマイズ。見出しタグの何番目、最後を判定し任意の内容を追加することができます。
~ 目次 ~
h3タグの1回目と2回目で処理を分岐した場合
functions.php
/*----------------------------------------------------
指定タグの何回目といった処理を行いたい場合
----------------------------------------------------*/
if ( !function_exists( 'replace_time_tag' ) ){
function replace_time_tag($the_content) {
$target_tag = '/<h3.*?>.+?<\/h3>/i';
$add_tag[0] = '<p>1回目</p><hr>'; // 1回目のタグの前に追加したい内容
$add_tag[1] = '<p>2回目</p><hr>'; // 2回目のタグの前に追加したい内容
// 記事ページ詳細
if(is_single()) {
if(preg_match_all($target_tag, $the_content, $match_tags)) {
// 1回目の該当タグが存在する場合
if (isset($match_tags[0][0])) {
// 追加したい記述をタグの前に追加
$the_content = str_replace($match_tags[0][0], $add_tag[0] . $match_tags[0][0], $the_content);
}
// 2回目の該当タグが存在する場合
if (isset($match_tags[0][1])) {
// 追加したい記述をタグの前に追加
$the_content = str_replace($match_tags[0][1], $add_tag[1] . $match_tags[0][1], $the_content);
}
}
}
return $the_content;
}
add_filter('the_content','replace_time_tag');
}
最後のh3タグの前にコンテンツを追加したい場合
functions.php
/*----------------------------------------------------
指定タグの最後のタグで処理を行いたい場合
----------------------------------------------------*/
if ( !function_exists( 'replace_last_tag' ) ){
function replace_last_tag($the_content) {
$target_tag = '/<h3.*?>.+?<\/h3>/i';
$add_tag = '<p>最後のタグ</p><hr>';
// 記事ページ詳細
if(is_single()) {
if(preg_match_all($target_tag, $the_content, $match_tags)) {
$last_key = array_key_last($match_tags[0]);
// 該当タグの最後のタグが存在する場合
if ( $last_key ) {
if (isset($match_tags[0][$last_key])) {
// 追加したい記述をタグの前に追加
$the_content = str_replace($match_tags[0][$last_key], $add_tag . $match_tags[0][$last_key], $the_content);
}
}
}
}
return $the_content;
}
add_filter('the_content','replace_last_tag');
}
画像の場合の正規表現サンプル
$target_tag = '/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*).+?\/?>/i';
ページ指定の条件補足
// 固定ページ、投稿ページ、カスタム投稿ページ
is_single()
// 固定ページ
is_singular('page')
// 投稿ページ('post')
is_singular('post')
// 特定のカスタム投稿ページ
is_singular('news')
// 投稿IDを指定したい場合
is_single($post->id)



