How to Detect if You Are on a Mobile Device with WordPress

When building a website, it is useful to be able to detect if you are on a mobile device or not. The main purpose of such a feature is to be able to better manage your page’s weight, but it can also be used to hide or display content based on the type of device you are on.

Before using this function, please keep in mind that mobile detection is not a replacement for using media queries and a responsive framework, but rather a complement that can help you fine-tune your WordPress theme.

The wp_is_mobile() function

WordPress provides this useful function to allow you to detect if you are on a mobile device. It runs a series of tests based on the request’s user agent and sends back TRUE or FALSE based on the test results. You can see the details of the function in the vars.php file.

It is perfect to be used as an if conditional statement, for example:

<?php
if ( wp_is_mobile() ) {
	/* Do stuff for mobile here */
} else {
	/* Do stuff for laptops and desktop here */
}
?>

Mobile Detect plugin

If you want to take it a step further, you should consider using a plugin to do the task. For that purpose, I would suggest using Mobile Detect, a free WordPress plugin based on a lightweight PHP class that is also named Mobile Detect.

This way, you will be able to fine-tune your request and make it go further. The plugin was developed to extend the possibilities of WordPress’ wp_is_mobile() function, but you can also use the class’ methods, for example:

$detect = new TinyWP_Mobile_Detect;
if ($detect->isMobile()) {
  # do stuff for mobile visitors
}
Tags: