How To Better Detect Your Mobile Visitors with WordPress’s WP_is_mobile Function

Although WordPress themes typically use Responsive Web Design to tailor websites for mobile devices, sometimes you may need to use PHP (the language WordPress is written in) to detect whether your visitor’s web browser is running on a mobile device. For example, you may want to output certain HTML markup (such as a mobile navigation menu) on mobile devices. Alternatively, you may only want to output a slider containing large images on desktop and not mobile devices. Doing this via PHP (instead of CSS) means that your visitor’s mobile browser won’t have to download all of the slider images even though the slider is never displayed, which also means that your site will load faster for your mobile visitors.

wp_is_mobile() is a function built into WordPress that detects whether the visitor is using a mobile device such as iPhone, iPad, Android, Silk, Kindle, BlackBerry, Opera Mini, and Opera Mobi. This is a conditional function, which means it returns one of two results: true or false. It’s located in wp-includes/vars.php.

The function was introduced in WordPress 3.4, and it can be used in a WordPress plugin or theme.

Here’s a simple example:

if ( wp_is_mobile() ) { // Visitor is on a mobile device} else { // Visitor is on a desktop (not mobile) device}

WordPress core currently uses this function in a few different places:

  • To completely disable the Visual Editor for Opera Mini.
  • To enable jQuery UI Touch Punch in the WordPress dashboard for mobile devices.
  • To detect whether the current device can upload files.
  • To disable the “shake” effect on the WordPress login page when an incorrect username or password is entered using a mobile device.

You can also use this function to hold mobile-specific content, such as the navigation menu mentioned above. <?php if ( wp_is_mobile() ) {
/* Display and echo mobile specific stuff here */
} ?>