I have no idea if anyone’s done this yet. But I’m a curious guy. I’ve optimized my WordPress blog for the iPhone. Making it compatible wasn’t an issue; the built-in Safari browser is pretty good. But I wanted iPhone users to find the blog immediately readable without the need to zoom in.
I didn’t want a new CSS for other web visitors, just something unique for iPhone users. I’m posting my methodology so others can hack it to bits take advantage of my solution.
First, I created an iPhone-specific CSS variant of my standard theme. First I got rid of the (admittedly ugly) graphic header. Then I made everything a max of 320px wide, the narrow width of the iPhone’s screen. Then I shoved the navigation menu to the bottom, just to get it out of the way (this could certainly be done better). Ok, that gave me an iPhone-optimized CSS. I named it style-iphone.css, and dropped it into my theme folder. You can view the CSS (far from beautiful, based on the xblog theme).
Ok, that part was easy. Now I wanted to get the iPhone to use it. So in the theme’s header.php I added:
<?php
$iphone_stylesheet = str_replace(“.css”, “_iphone.css”, get_bloginfo(‘stylesheet_url’));
?>
<link media=”only screen and (max-device-width: 480px)” href=”<?php echo $iphone_stylesheet; ?>” type=”text/css” rel=”stylesheet” />
So that basically changes style.css to style_iphone.css, and uses the new Apple-defined media type. In other words, this tells the iPhone to use this stylesheet, and everything else to ignore it. I put this after the normal stylesheet line, not sure if that was required or not.
Worked great, but I wanted the iPhone to zoom right into my blog instead of forcing the user to double-tap. That’s where the Viewport meta tag comes in. I wasn’t sure what Viewport might do to non-iPhone browsers, so I wrapped that in a PHP test:
<?php
if (strstr($_SERVER['HTTP_USER_AGENT'], “iPhone”))
{
echo ‘<meta name=”viewport” content=”width = 320″ />’;
}
?>
So my header.php now looked like this:
<link rel=”stylesheet” href=”<?php bloginfo(‘stylesheet_url’); ?>” type=”text/css” media=”screen” />
<?php
$iphone_stylesheet = str_replace(“.css”, “_iphone.css”, get_bloginfo(‘stylesheet_url’));
?>
<link media=”only screen and (max-device-width: 480px)” href=”<?php echo $iphone_stylesheet; ?>” type=”text/css” rel=”stylesheet” />
<?php
if (strstr($_SERVER['HTTP_USER_AGENT'], “iPhone”))
{
echo ‘<meta name=”viewport” content=”width = 320″ />’;
}
?>
(That first stylesheet line is unchanged, as a frame of reference.)
And voila. iPhone users now see a very readable, optimized blog. Users from anything else don’t see any difference.
I’m using a somewhat old WordPress (2.0.6); I’m not sure if the header in 2.2 is any different, but the solution shouldn’t be different.
I’m very curious what others think of this implementation.
Technorati Tags: iPhone