WordPressでAMPページと通常ページを判別する方法を紹介します。GoogleがAMPを強力に推奨しており、このサイトでもAMPページの閲覧数が増えてきました。

AMPページかどうかを判別する関数
WordPressをAMP対応する場合、プラグイン「AMP」を使う方法がシンプルで簡単です。
プラグイン「AMP」を使っている場合、関数is_amp_endpoint()を使って、AMPページかどうかを判別することができます。
// AMPチェック AMPだとtrue, 非AMPだとfalseを返す
$myAmp = false;
if(function_exists('is_amp_endpoint') && is_amp_endpoint()) {
$myAmp = true;
}
AMPページの場合$myAmp = true、通常ページの場合$myAmp = falseとなります。
AMPページにAdsense広告を挿入する方法
例えば、AMPページ末尾にAdsense広告を挿入するときには、下記のコードをfunctions.phpに記入します。
function add_ad_after_content($the_content) {
// AMPチェック ampだとtrue, 非ampだとfalseを返す
$myAmp = false;
if(function_exists('is_amp_endpoint') && is_amp_endpoint()) {
$myAmp = true;
}
// AMPページの場合
if($myAmp) {
// AdSenseタグ
$ad = <<< EOF
<div class="ad-container">
<amp-ad width="336" height="280" type="adsense"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="3708412355"></amp-ad>
</div>
EOF;
// 本文末尾にAdsenseタグを追加
$the_content = $the_content.$ad;
}
return $the_content;
}
add_filter('the_content','add_ad_after_content');
AMPページでのAdsense広告は下記のような記述方法になります。
<amp-ad width="336" height="280" type="adsense" data-ad-client="ca-pub-0000000000000000" data-ad-slot="3708412355"></amp-ad> </div>
Adsenseの広告コードからdata-ad-client="ca-pub-0000000000000000"とdata-ad-slot="3708412355"の部分を使います。
data-ad-client="ca-pub-0000000000000000" data-ad-slot="3708412355"