Quick-Tip: Natively Detecting iPhone Users in WordPress

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:

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:

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:


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!



Related Articles