WordPressでAMPページの出しわけ「is_amp関数」を作る
※記事の情報は執筆時点のものとなります(5年前の投稿)
AMP対応すると、ちょこちょこ出しわけしたい場所が出てきます。
- ページによっちゃAMPにしたくない
- AMPの場合は特定のモジュール出したくない
- AMPの場合だけ特定の広告を出したい
というわけで条件分岐が必要。
簡単な関数を作りました。
- スポンサーリンク
「is_amp関数」を作る
WordPressでAMPのテンプレートを出すのにパラメータを使っている前提です。
URLに「?amp=1」でAMPのテンプレを出す
↑こういう人ね。
function.phpにチャチャっと書いちゃいましょう。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// AMPページの判断 | |
function is_amp() { | |
if(isset($_GET['amp']) && $_GET['amp'] == 1){ | |
return true; | |
} else { | |
return false; | |
} | |
} | |
?> |
使い方はこんな感じ。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if(is_amp()) { | |
// こちらがAMPがONのとき(パラメータに?amp=1がついているとき) | |
} else { | |
// こちらがAMPがOFFのとき(パラメータがない、もしくは?amp=1じゃないとき) | |
} | |
?> |
これでampの時の出しわけ記述は楽チンになります。
アフィリエイトとか広告表示をAMPのときにが切り分けたい。なんてときは、ショートコードとかでこの「is_amp関数」を使って出しわけできます。
例によっていろいろな場所で使いまくるとメンテが複雑になったり、重い原因になりますのでご注意を。
※記事で紹介したコードは動作を保証するものではございません。必ず自己責任で使用してください。コードを使う際はテストを行い、動作検証をおこなってください。
