I screwed up not that long ago.
I got an email from Google Adsense telling me that one of my sites was in violation because it was showing two ads on the same mobile screen, which is not allowed. Until I started using some of Googles whole page on mobile ads (an experiment), this was never an issue. Now it was. Now I had to fix it.
Thankfully I knew the simpliest answer would be to detect if a page was mobile and not display the ads. Among other things, I know that I hate too many ads on mobile. So all I wanted was to use the Google page level ads – one ad for the mobile page, easily dismissible. Therefore it would be best if I hide all but two other ads. One isn’t really an ad as much as an affiliate box, and one Google responsive ad.
For my mobile detector, I went with MobileDetect, which is a lightweight PHP class. I picked it because I was already using PHP to determine what ads showed based on shortcodes so it was a logical choice.
Now the way my simple code works is you can use a WordPress shortcode like [showads name="google-responsive"]
and that calls a file, passing a parameter for name into the file to generate the ad via a mess of switches and sanitation. Really you can go to http://example.com/myads.php?name=leaderboard
and it would show you the ad.
The bare bones of the code looks like this:
<?php require_once 'Mobile_Detect.php'; $detect = new Mobile_Detect; $thisad = trim(strip_tags($_GET["name"])); $mobileads = array('google-responsive', 'affiliate-ad'); // If it's mobile AND it's not in the array, bail. if ( $detect->isMobile() && !in_array($thisad, $mobileads) ) { return; } echo '<div class="jf-adboxes '.$thisad.'">'; switch ($thisad) { case "half banner": echo "the ad"; break; case "line-buttons": echo "the ad"; break; default: echo "Why are you here?"; } echo '</div>';
The secret sauce is that check for two things:
- Is the ad not one I’ve authorized for mobile?
- Is this mobile?
Only if both are false will the script continue to run. It’s simple but I like to have things stop as soon as possible to make loading faster. There’s no css trickery to hide things via mobile size detection. It’s as simple, and as close to a binary check as I can make it.