Menu

How to detect mobile visitors in your WordPress theme or plugin

There are plenty of solutions for making your WordPress website mobile friendly. Most of them redirect to a separate mobile friendly theme. However this may be overkill for certain sites which just require a few minor changes to look right on a mobile device. This solution could be used for example to load a separate style sheet for mobile devices or to only show a javascript photo slider on desktop PCs.

First download Mobile_Detect.php from https://github.com/serbanghita/mobile-detect and add the file to your theme folder.

Then open the template file you wish to include your mobile specific changes e.g. header.php file in a text editor and add the following:

<?php
include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile()) {
 // code to run for mobile devices
} else {
 // code to run for desktop browsers
}
?>

If you just want to detect certain mobile devices like android phones then you can use the following:

if ($detect->isAndroid()) {
    // code to run for the Google Android platform
}

Available methods in Mobile_Detect.php include isAndroid(), isAndroidtablet(), isIphone(), isIpad(), isBlackberry(), isBlackberrytablet(), isPalm(), isWindowsphone(), isWindows(), isGeneric().

There are now WordPress plugins available such as WordPress Mobile Detect that use this script so you can use shortcodes to hide/show content in your blog posts based on whether you’re using a mobile device. There are also plugins like WP247 Body Classes which add CSS classes to show the type of device your visitors are using.