Hide adsense ads for Wordpress admin with GTM

Most of WP admins who don’t like to serve ad impressions while editing / previewing blog posts nor want to use browser plugins like AdBlock (that creates file upload and lot other issues)

In this tutorial, we will discuss of blocking Adsense ads whenever a user is logged in with Admin or Editor permissions using Google Tag Manger.

Plan: (1) detect user-type in WP (2) trigger a GTM custom event data-layer for based on user-type (3) based on event – control the adsense tag parts to block the ads

Below PHP code will conditionally detect if the user type is Editor or Admin and echos value based on the rules.

<?php
if ( current_user_can('editor') || current_user_can('administrator') ){
 echo "noAds";
}
else {
 echo "showAds";
};
?>

Above code will work for both “editor” and “administrator”, in case if you want only administrator to be blocked and delete off

current_user_can('editor') ||

and it will be:

<?php
if ( current_user_can('administrator') ){
 echo "noAds";
}
else {
 echo "showAds";
};
?>

After adding PHP script to  GTM event datalayer script:

<script>
 dataLayer = [{
'event': '<?php if (current_user_can('administrator')){ echo "noAds"; } else { echo "showAds"; }; ?>'
 }];
</script>

So, above code will send GTM event “noAds” if user is admin and send “showAds” if user is not a  admin.

Now we want to configure GTM,  before that I hope you know that for AdSense to trigger an ad, it needs a line of JS code to be executed at least once in the content page .

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

And  this is the script that we will be controlling in GTM. So, keep in mind that above code should not be anywhere in content other than at GTM.

Now let us create custom HTML tag in GTM for

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

and create a new firing trigger (selecting more)  based on  custom event “showAds”.

We are done! now publish the tags and have a preview in GTM.