Created
December 10, 2019 03:01
-
-
Save mhige/317dc3768fef47209befc265cc318e03 to your computer and use it in GitHub Desktop.
AMPを表示したいページとしたくないページを切り分ける例
This file contains 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のURLを表示する関数 | |
function amp_link_tag(){ | |
// 例えばA8.netのアフィリエイトがあるページはAMP表示しない場合 | |
// 記事の投稿情報をとってくる | |
$content = apply_filters('the_content', get_post_field('post_content', get_the_ID())); | |
// preg_matchで$content内のA8のURLをマッチングさせる | |
$no_amp_a8ad = preg_match('/<a.*?href="https:\/\/px\.a8\.net/is', $content); | |
// ここに複数条件を入れる | |
// 記事ページだけ表示する | |
// モバイルの時だけ表示する(is_mobile関数を作っている前提) | |
// $no_amp_a8ad にマッチしていない時だけ表示する(なので「!」を入れる) | |
if(is_singular('post') && is_mobile() && !$no_amp_a8ad){ | |
// パラメーターを変数に入れる | |
$amp_param = '?amp=1'; | |
// URLを取得してパラメーターの入った変数とつなぎ、echoする | |
echo '<link rel="amphtml" href="'.esc_url(get_permalink()).$amp_param.'">'."\n"; | |
} | |
} | |
// add_actionで実際に関数が実行され、タグが挿入される | |
add_action('wp_head','amp_link_tag'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment