How To Detect Mobile Device From WordPress Theme

Did you ever think about presenting different part of your theme’s template file for mobile device? Or did you ever think to show different contetn for mobile devices who visits a WordPress site using a mobile device? For example you want to show “You are on PC” text on a place of your WordPress theme and “You are on mobile” text for those who browse your WordPress site on mobile device.

Obviously you need to find a way that detect mobile or PC device and after detecting it you would like to show different content depending upon the device – mobile or PC/Desktop. Now I am going to show you through this post how you can detect mobile device and depending upon that how you can present different content.

May be you want to load a different template file for mobile that is perfectly boosted and lite weight for mobile devices. But before doing this you need a way to detect if your WordPress site is is browsing from mobile or PC.

How to detect mobile device on your WordPress site from theme?

Luckily WordPress has a function that detect mobile device. This function will let you easily detect if the visitors of your WordPress site is on mobile or on computer. wp_is_mobile() is a easy to use function that will let you detect if the users who browsing your WordPress site with a mobile device or from computer. And believe me it is very easy to do that with using the inbuilt wp_is_mobile() function of WordPress core. Here is an example that using wp_is_mobile function with if condition:

<?php
if ( wp_is_mobile() ) {
    echo "You are on mobile device";
}
?>

The above code represent as if the device is mobile then show the text “You are on mobile device”.



Now again look at the below code with few changes:

<?php
if ( !wp_is_mobile() ) {
    echo "You are on computer";
}
?>

The above code represent that if the device is not mobile then show text “You are on computer”.

Now look at the below code which can be really so helpful for theme development:

<?php
if ( wp_is_mobile() ) {
    get_template_part("mobile_index");
}
?>

The above code represent as if the device is mobile then load mobile_index.php file. Here mobile_index.php file is specially built for mobile so that it will load at faster speed. The wp_is_mobile() function will detect all the tablet device also as mobile device.

So did you understand how you can detect mobile device from your WordPress theme. All the credits goes to wp_is_mobile() function which makes it easier for theme developers to detect if the user is using mobile device or a PC.

Leave a Reply

Your email address will not be published. Required fields are marked *