In 2024, mobile friendliness remains an essential requirement for building effective WordPress websites. Following Google’s Mobilegeddon updates to its mobile search algorithm, which took effect on April 21, 2015, webmasters and developers have continued to feel the urgency to optimize their websites. This optimization is crucial to maintain or improve search engine rankings in an increasingly mobile-centric digital landscape.
Today, we will explore how to detect mobile and tablet devices in WordPress. Even if your WordPress site is already optimized for mobile viewing, there are additional tweaks you can implement to enhance performance and loading speed on mobile devices. For instance, you may want to hide certain elements, such as sidebars or specific advertisements, when users access your site from mobile devices.
While WordPress offers a built-in function,wp_is_mobile()
, to detect mobile devices, it does not differentiate between mobile phones and tablets. To address this limitation, you can utilize the Mobile Detect PHP library, which allows for more granular detection. You can download the lightweight Mobile Detect PHP source from GitHub and place theMobile_Detect.php
file into yourwp-content/themes/your-theme/
directory.
Next, you will need to create new functions in your theme’sfunctions.php
file:
php
/ Check if the user is on a smaller mobile device /
function my_wp_is_mobile() {
include_once ( get_template_directory() . '/Mobile_Detect.php' );
$detect = new Mobile_Detect;
if( $detect->isMobile() && !$detect->isTablet() ) {
return true;
} else {
return false;
}
}
/ Check if the user is on a tablet device /
function my_wp_is_tablet() {
include_once ( get_template_directory() . '/Mobile_Detect.php' );
$detect = new Mobile_Detect;
if( $detect->isTablet() ) {
return true;
} else {
return false;
}
}
With these functions, you can conditionally display or hide elements in your theme based on whether the user is on a mobile or tablet device. For example, if you want to prevent the sidebar from displaying on mobile devices, you can use the following code:
php
/ Sidebar will show on desktop/tablet but not on mobile devices /
if( my_wp_is_mobile() ) {
// Do not display sidebar
} else {
get_sidebar();
}
?>
For more advanced conditional mobile detection, including browser and operating system detection, you can refer to the Mobile Detect documentation. We hope this tutorial proves helpful in enhancing your WordPress site’s mobile optimization. To see the differences in action, consider testing your site on both mobile and tablet devices.