How to Detect Mobile or Tablet Condition in WordPress

detect mobile and tablet condition
Mobile friendliness has becoming a must need condition for building a website nowadays. With the Google’s Mobilegeddon updates on mobile search algorithm effective starting on 21 April 2015, many webmaster and web developer starting to feel the pressure on updating their websites or client’s website so it won’t effect how well their sites rank in Google search engine.

Today, we are going to learn how to detect mobile or tablet device in WordPress. Sometime even if you already optimize your WordPress site for mobile viewing, there’s still a few tweak that can help you optimize even more so your sites will load faster in mobile devices. for example you do not want to show some element like sidebar or different advertisement options to show whenever you in mobile or tablet device.

[sc_amazon title=”” design=”grid” search=”Mac”]
Using WordPress built-in function wp_is_mobile is a great way to detect mobile, however this function did not distinct if the user using mobile or tablet device. Because you prefer to show less stuff when user in smaller mobile device (not tablet), you would want to separate the two condition between them, here’s where mobile detect php comes in handy.

You can download copy of lightweight mobile detect php github source. Copy the Mobile_Detect.php into your wp-content/themes/your-themes/

Create a new function inside your theme functions.php.

[php]/* check if user using 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 user using 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;
}
}[/php]

With this function, you can wrap any element in your theme to reflect the on and off condition between mobile and tablet device.

if you do not want to show sidebar in mobile device, try something like this

[php]<?php
/* sidebar will show in desktop/tablet but not mobile device */
if( my_wp_is_mobile() ) { } else { get_sidebar() };
?>[/php]

You can check out more conditional mobile detect in their website which include browser and device OS detect. Hope you find the tutorial helpful and help you improved your WordPress site mobile optimization. Want a live sample?, try browsing this site in mobile device vs tablet device, you will see the difference.

Comments are closed.

Scroll to Top