functionphpで記事内に表示させる内容を固定させる
function add_ad_before_h2_for_3times($the_content) {
//広告を自動挿入する
$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][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');
参考:https://gist.github.com/09045392431/a52c06a182887fb3c2c498eb59832b60
function add_ad_before_h2_for_3times($the_content) {
//広告を自動挿入する
$ad = <<< EOF
//////////////////////////////////
//ここに広告コード&アドセンスコード//
//////////////////////////////////
EOF;
$ad が指定する内容に当たる。
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][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');
で分岐を行う。
h2の順番の指定方法とかに関しては後日まとめる!
ココがよく理解できてないので確認すること。
add_filter('the_content','add_ad_before_h2_for_3times');
久しぶりの覚書。
この記事が気に入ったらサポートをしてみませんか?