Although WordPress themes typically use Responsive Web Design to tailor website for mobile devices, there is sometimes a need to use PHP (backend code) to detect whether the visitor’s web browser is running on a mobile device.
For example, there may be scenarios where 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 the visitor’s mobile browser won’t have to download all of the slider images even though the slider is never displayed.
WordPress’ wp_is_mobile() function to the rescue!
wp_is_mobile() is a litte-known function built into WordPress that detects whether the visitor is using a mobile devices such as iPhone, iPad, Android, Silk, Kindle, BlackBerry, Opera Mini, and Opera Mobi.
The function was introduced in WordPress 3.4, and it can be used in a WordPress plugin or theme.
It’s a simple function that accepts no parameters, and returns a simple boolean (true/false) value.
Here’s a simple example:
Interestingly, 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.
Are you currently using the
wp_is_mobile() function in your plugin or theme? If so, I’d love to hear what your use-case is.