How To Detect Mobile Device in WordPress & Show Different Ads

This little tutorial will show you how to detect a mobile device or mobile reader in WordPress and then display a different ad or content based on the device being used. This tip is useful if you are using a responsive WordPress theme and want to show different ads to desktop and mobile readers.

WordPress has an inbuilt function called: wp_is_mobile() which checks if a visitor is using a mobile device or not. In the example below we will use this function inside single.php to display a different ad to visitors using a desktop browser and those using a mobile browser.

<?php if (wp_is_mobile()){ ?>
<!-- INSERT AD 1 HERE FOR MOBILE USERS -->
<?php } else{ ?>
<!-- INSERT AD 2 HERE FOR DESKTOP USERS -->
<?php }; ?>

That’s it! For your reference the wp_is_mobile function is defined in WordPress core file: wp-includes/vars.php and here is the actual function:

function wp_is_mobile() {
	static $is_mobile;

	if ( isset($is_mobile) )
		return $is_mobile;

	if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
		$is_mobile = false;
	} elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
		|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
		|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
		|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
		|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
		|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false ) {
			$is_mobile = true;
	} else {
		$is_mobile = false;
	}

	return $is_mobile;
}

Divi WordPress Theme

Leave a Reply

Be the First to Comment!

Leave a Reply


wpDiscuz