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>
</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).