WordPress has embraced the mobile revolution from the first moment. We have apps for iOS or Android and all the WordPress blogs can be accessed in iPad format. We also have in WordPress core a variable to detect if the user is visiting the site using an iPhone device. In this tutorial we will learn how to apply a class using WordPress’ body_class based in that variable.
The variable we will be using is $is_iphone, and is defined at vars.php as follows:
if ( $is_safari && stripos($_SERVER['HTTP_USER_AGENT'], 'mobile') !== false ) $is_iphone = true;
All we have to do is instance the global variable in our WordPress theme, test if it’s true and do something:
<?php global $is_iphone; if($is_iphone) $iphone_class = 'iphone'; ?> <body <?php body_class($iphone_class); ?>>
With this simple code, you can apply a specific CSS class to the body tag if someone is visiting your site using an iPhone. Of course, you can do a lot of other things, like applying a new stylesheet. A new CSS file is much better than rely on media queries, since the CSS will dictate which images must be specifically downloaded. Using media queries, all images defined in the CSS file are downloaded.
<?php global $is_iphone; if($is_iphone)?> <link rel="stylesheet" href="/iphone.css" media="only screen and (max-device-width: 480px)"> <?php else ?> <link rel="stylesheet" href="/common.css" media="screen">
Chances are that you’re overring WordPress internal body_class using your own class generator, so you can just add the following in your code, assuming $classes is the array where you are storing your CSS classes to be outputed:
if($is_iphone) $classes = 'iphone';
With little effort we now have our site prepared to detect the browser of an iPhone device. If you’re wondering why there is not an $is_android variable, I’m wondering that too, but anyway, you can always fake one by sniffing the $_SERVER['HTTP_USER_AGENT'] variable.