Inserting AdSense code right after </head> tag

i would like to to add an AdSense activation code to my Wordpress site.

Google says it needs to be inserted right AFTER the tag

I have tried the plugin Snippets, yet it seems not to be working.

The code is:

script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
/script 
script   
(adsbygoogle = window.adsbygoogle || []).push(
{     google_ad_client: "ca-pub-5316020100281676",
enable_page_level_ads: true   }); 
/script

Thanks in advance.

Topic adsense Wordpress

Category Web


Maybe they changed their requirements? Google says it needs to be inserted BETWEEN the tags. See here:

Implementing code into WordPress page (Google manual (GER)

There are two ways to realize it:

  • Use a plugin to paste code into section.
  • Or do it manually: create copy of header.php and save it securely. Then open header.php in a text editor and paste AdSense code just BEFORE closing tag.

Without using a plugin, the WordPress way would be to use the wp_head action to insert the script and then enqueue the script file:

function mytextdomain_adsense() {
    $output="
    <script>
      (adsbygoogle = window.adsbygoogle || []).push({ 
        google_ad_client: 'ca-pub-5316020100281676',
        enable_page_level_ads: true   
      });
    </script>";

    echo $output;
}
add_action('wp_head','mytextdomain_adsense');

function mytextdomain_adense_script() {
    wp_enqueue_script( 'my-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'mytextdomain_adense_script' );

And to add the async attribute to the script link:

function mytextdomain_add_async_attribute($tag, $handle) {
    if ( 'my-adsense' !== $handle ) {
      return $tag;
    }
    return str_replace( ' src', ' async src', $tag );
}
add_filter('script_loader_tag', 'mytextdomain_add_async_attribute', 10, 2);

This should be placed in the theme's functions.php file (preferably a child theme so that it doesn't get overwritten if there's a theme update).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.