Advertisement

Quick-Tip: Natively Detecting iPhone Users in WordPress

by

With the rapid growth of smart phone users, it has become increasingly important in web development to ensure visitors who access your website through handheld devices are catered to appropriately. There are a number of ways in which these visitors can be targeted, and in this tutorial we will explore creating a function to natively detect iPhone users in WordPress.


Step 1 Writing the Function

Ensure you paste the function before the closing </head> tag. By default, the TwentyEleven and TwentyTen themes use the body_class(); function in the header.php file to dynamically add classes to the standard <body> tag.

For example, if you are viewing a single page in WordPress, <body class="singular"> is an example of a body class for a singlular page/post, which would allow you to change the style of certain elements of your design dynamically using CSS. If your theme doesn’t use the body_class(); tag (even though it really should be doing that already!), go ahead and include it, like this:

<body <?php body_class(); ?>>

WordPress has a number of global variables which can be used for browser detecting, including the $is_iphone variable. We will be using this variable along with the body class system in WordPress. To do that, we must first write a function:

<?php
function detect_iphone($iphone) {
	global $is_iphone;
	if($is_iphone) $iphone[] = 'iphone';	
	return $iphone;
}
add_filter('body_class','detect_iphone');
?>

This is our function. Firstly, we give our function a name of “detect_iphone” so that we can decipher it from our other functions. You will then notice added “global” to our $is_iphone variable, this is because the variable is defined outside of our function. We then tell WordPress that if this condition is met (if the user is browsing the site from an iPhone), to add “iphone” to our body class. Go ahead and paste this snippet of code above the closing </head> tag in header.php


Step 2 Targeting iPhone Users With CSS

This function now allows us to specifically target iPhone users using CSS, by using our newly created “iphone” class. For example, we may include the following in our stylesheet to display our h1 tag differently to iPhone users:

h1 {
font-size: 30px;
line-height: 110%;
text-decoration: underline;
}

.iphone h1 {
font-size: 35px;
text-decoration: none;
color: #FF0000;
}

Conclusion

There are an increasing number of methods to make WordPress sites friendly for our mobile audience, and I hope this quick-tip has helped you to understand another approach at tackling mobile-friendly sites.

I encourage you to discuss your own preferred methods of making your WordPress sites mobile-friendly in the comments below!

Advertisement