Categories
Wordpress Initial Setting

Adsense Auto-Ads (via functions.php)

My recommendation for adding Google adsense auto-ads code is to use a plugin. But I personally use below, and paste those in functions.php.

【Last updated: April 2020】

My recommendation for adding Google adsense auto-ads code is to use a plugin. But I personally use below, and paste those in functions.php.

Adsence Auto-Ads for non-AMP

<?php function additional_head_script() {
    if ( is_single() && !is_user_logged_in() ): ?>
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-XXXXXXXXXXXXXXXX",
    enable_page_level_ads: true
  });
</script>
<?php endif; }
add_action( 'wp_head', 'additional_head_script' );
?>

Note-1: XXXX part has to be changed to your own account ID.

Note-2: I add extra conditions to limit ads on single pages, and also avoid clicking the ads when I am checking my page or my preview. So, if you wishes to test the code, please go to the incognito window.

Reference: WordPress Codex, is_user_logged_in(), is_single( int|string|int[]|string[] $post = ” )

Adsense Auto-Ads for Accelerated Mobile Page

<?php function amp_additional_head_script () {
    $url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    if (strpos($url,'amp') !== false): ?>
        <script async custom-element="amp-auto-ads"
        src="https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js">
        </script>
<?php endif;
}
add_action( 'wp_head', 'amp_additional_head_script' ); ?>
<?php function amp_additional_body_script () {
    $url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    if (strpos($url,'amp') !== false): ?>
        <amp-auto-ads type="adsense"
        data-ad-client="ca-pub-XXXXXXXXXXXXXXXX">
        </amp-auto-ads>
<?php endif;
}
add_action( 'wp_body_open', 'amp_additional_body_script' ); ?>

Note-1: Condition is URL contains the word “AMP”, so if your AMP mode does not contain any suffix, it will not work.

Thanks!

I am not so confident whether these codes are OK for coders. What I know is that these work well on my sites…

Hope this information helps.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.