So I’ve broken this up into three parts, it’ll allow you a lot more flexibility with adding additional authors if that ever comes up.
enqueue_adsense()
adds the Google scripts for adsense.
add_inline_adsense()
prints the adsense code to display the ad immediately across the top of the page, so right after the body tag.
function_js_async_attr()
is needed to add the async code to the script. You’ll have to update the list of scripts to exclude though as I don’t know what scripts you have running.
function enqueue_adsense() {
wp_enqueue_script( 'google-adsense', 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '', false );
}
add_action( 'wp_enqueue_scripts', 'enqueue_adsense', 2 );
function add_inline_adsense() {
global $post;
$author_id = $post->post_author;
//you'll want to adjust the author IDs in the following conditions to match what you need
if( $author_id == 1 ) :
$data_ad_client="12345678910";//these need to be changed
$data_ad_slot="66677666998";//these need to be changed
elseif( $author_id == 2 ) :
$data_ad_client="01987654321";//these need to be changed
$data_ad_slot="66677666998";//these need to be changed
endif;
echo '<ins class="adsbygoogle" style="display:inline-block;width728px;height:90px; data-ad-client=" . $data_ad_client . "" data-ad-slot="' . $data_ad_slot . '"></ins>';
echo '<script></script>';
}
add_action( 'wp_head', 'add_inline_adsense', 3 );
function js_async_attr( $tag ) {
$scripts_to_exclude = array(); //add a list of scripts that need to be excluded from async - 'script1.js', 'script2.js', 'script3.js'
foreach( $scripts_to_exclude as $exclude_script ){
if( true == strpos( $tag, $exclude_script ) ) :
return $tag;
endif;
}
return str_replace( ' src', ' async src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 102 );
I’ve tested this on a site I’m currently working on and it’s worked exactly as designed/intended.
If I was building this for a long term use site, I’d even go so far as to have an adSense ID field on user meta, then instead of running the condition that says if the author is X use adSense ID Y I’d just pull the author’s provided adSense ID number and only perform the rest of the functions IF an adSense ID has been provided. I don’t really have time to build that out right now though and it’s not in the scope of what you asked, but I think that’d future proof your project. 🙂