Skip to content

Instantly share code, notes, and snippets.

@webloglife
Created December 2, 2016 14:12
Show Gist options
  • Save webloglife/c3da1a5a0347a1677efb7df5e4d95c56 to your computer and use it in GitHub Desktop.
Save webloglife/c3da1a5a0347a1677efb7df5e4d95c56 to your computer and use it in GitHub Desktop.
amp-ad3
function add_ad_before_h2_for_3times($the_content) {
//広告(AdSense)タグを記入
$ad = <<< EOF
<div style="padding:15px 0px">
<p>スポンサードリンク</p>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 記事中 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXX"
data-ad-slot="XXXXXXX"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<!-- 記事中_AMP -->
<amp-ad
type="adsense"
data-ad-client="ca-pub-XXXXXXX"
data-ad-slot="XXXXXXX"
width="320"
height="100">
</amp-ad>
</div>
EOF;
if ( is_single() ) {//投稿ページ
$h2 = '/^<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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment