function add_ad_before_h2_for_3times($the_content) {
//広告(AdSense)タグを記入
$ad = <<< EOF
//////////////////////////
//////////////////////////
EOF;
if ( is_single() ) {//投稿ページ
$h2 = '/^.+?<\/h2>$/im';//H2見出しのパターン
if ( preg_match_all( $h2, $the_content, $h2s )) {//H2見出しが本文中にあるかどうか
if ( $h2s[0] ) {//チェックは不要と思うけど一応
if ( $h2s[0][0] ) {//1番目のH2見出し手前に広告を挿入
$the_content = str_replace($h2s[0][0], $ad.$h2s[0][0], $the_content);
}
if ( $h2s[0][1] ) {//2番目のH2見出し手前に広告を挿入
$the_content = str_replace($h2s[0][1], $ad.$h2s[0][1], $the_content);
}
if ( $h2s[0][2] ) {//3番目のH2見出し手前に広告を挿入
$the_content = str_replace($h2s[0][2], $ad.$h2s[0][2], $the_content);
}
}
}
}
return $the_content;
}
add_filter('the_content','add_ad_before_h2_for_3times');