Mobile browser detection for WordPress – embedded is_mobile() function
Lets face it. Responsive design is here to stay and it is the solution to all of our nightmares regarding mobile web design. For those who are not aware of this technique, I invite you to read my other post where I explain what it is. But lets get to the point. Sometimes we need to add conditionals to our WordPress theme in order to detect if the visitor is visiting us from a mobile device, if so, we remove or add content. This is solved by using a custom made function called is_mobile() embedded into our functions.php. Read on for more.
First of all, we need to add the is_mobile() function to our functions.php file inside our theme folder:
function is_mobile() { if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|sagem|sharp|sie-|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT'])) return true; else return false; }
Then you can call this function in any of your template files. Lets say you want to use a totally different stylesheet for mobile devices. You would use something like this:
<?php if (is_mobile()): ?> <!-- Mobile version or any other stuff you want to add for mobile --> <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/handheld.css" type="text/css" media="screen,handheld" /> <link rel="stylesheet" title="mobile_version" href="<?php bloginfo('stylesheet_directory'); ?>/handheld.css" type="text/css" media="handheld, only screen and (max-device-width:480px)" /> <?php else: ?> <!-- Normal version or any other stuff you want to add for normal display --> <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/core.css" type="text/css" media="screen" /> <?php endif; ?>
Easy peasy huh? The applications for this are endless, starting from alternate stylesheets to different images, JS files and even content. In fact, you can even redirect users to a mobile landing page using this function. Have fun with it and if you found an interesting application for this function, sound off in the comments below.