Feb 18 AT 3:17 PM Clark Wimberly 85 Comments

Tutorial: Making your WordPress blog Android and iPhone friendly


A few weeks ago we launched the new Android and Me mobile site to almost unanimously positive reviews. The outpouring of support for my first major mobile build really got me excited and to return the favor I wanted to try to share some of what I learned.

This article is intended for those who already have a web or WordPress background. If you don’t quite understand how to put together your own templates, this might not be for you. For a long time we used the excellent plug-in WPtouch, which is a great solution for those uncomfortable with building from scratch. This isn’t a simple fix, we are going to get our hands dirty.

Let me start by saying that the following advice is a random collection of things I picked up while building the Android and Me mobile site. I’ll also start by saying I’m not a professional mobile developer. I do, however, bring years of traditional web and WordPress experience to the table and have recently been dropped head first into the mobile world. I’ve been enjoying it immensely. These are my findings:

Detecting mobile devices

The first step in creating a mobile site is detecting the devices trying to access your pages. The newest version of WordPress (2.9+) has made this a rather simple task with a new, built-in in conditional tag: is_iphone. Documentation on the function is hard to come by (it isn’t in the WordPress conditional tag list) but so far it’s proved to be an extremely elegant solution to selectively serving mobile templates to mobile users.

I found is_iphone on accident while digging through the WP core files and tested it on our development server and it returns true for Android as well (I’m guessing because it’s looking for the webkit browser agent). And using it is easy. The basic structure is like so:

<?php if ( $is_iphone ) {?>
     // mobile template
<?php } else { ?>
     // regular template
<?php } ?>

So, for example, if you wanted your single entry template (single.php) to check the device and serve the proper template, you could do so like this:

<?php if ( $is_iphone ) {?>
     <?php include( TEMPLATEPATH . '/mobile/single.php' ); ?>
<?php } else { ?>
     // entire contents of your regular single.php template
<?php } ?>

The above code is rather simple. If WordPress determines the browser is run on an iPhone (or Android device) it will know to use your specific mobile template (I’ve put all my mobile templates within a /mobile folder). Within your mobile templates you can use WordPress functions the same as you would in any other template. I’ve even got my mobile templates broken down into smaller pieces (as is customary when templating) like a mobile-specific header, footer, etc. In a regular template to call the header you can use the function:

<?php get_header() ?>

My mobile header is a completely different beast than the desktop header. It contains far less scripts and contains many key pieces needed to complete my mobile layout. So I created a new header, located within /mobile and within my mobile templates I can call it like so:

<?php include( TEMPLATEPATH . '/mobile/header.php' ); ?>

At the time, the is_iphone conditional seems to only return true for iPhone and Android users. Palm and BlackBerry users appear to be left in the dark. If that bothers you, there are many other ways to detect mobile users but for our purposes Android and iPhone cover our target audience. If that offends you as a Pre user, prove me wrong and show up in our analytics.

Also, since it’s an official WordPress function, hopefully they will expand it in the future to cover other smartphone platforms. In fact, I propose we change the tag’s name while it still fresh to is_smartphone.

Making things looks right

The great thing about designing and coding for a mobile device nowadays is just how awesome smartphone browsers have become. There are almost no differences between your markup for desktop and for mobile (with the exception of target device screen size). It’s the same site, only lightweight and smaller. Cut out whatever extra jazz you can, but for the most part the Android browser can handle the load.

The main concern is screen real estate. I’ve collapsed our three column desktop site into a single column for mobile. The site retains the same look and feel but is much more efficient on smaller screens.

Also with a small screen usually comes content that is much too large for the device, which is why smartphones have something called a viewport. The viewport is a screen sized looking glass that lays over a much larger page. Everything you see on the screen is within the viewport. Everything you can’t see is not.

With Android 1.6 came support for different screen resolutions (and thus different viewport sizes). To level the playing field we can add a custom meta tag to our mobile site’s header (/mobile/header.php)

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;" />

The viewport will be sized automatically to screen width (320px, 480px, etc) and will be zoomed to a scale of 1.0 (preventing the site loading waaaay zoomed out with everything very tiny). We’ve also set the viewport to not be user-scrollable, which will give our site a much more app-like feel. If you’d like the users to be able to zoom in and out, this would be the time to decide such.

When a phone is rotated and the orientation switches, the viewport resizes. Because of the ever changing screen widths, it’s important for your layouts to be fluid. When I first got my Nexus, I was worried the wider screen width would lead to odd layout challenges (images aren’t as easy to make fluid) but setting the scale and zoom to 1.0 makes the images appear the same size on all devices.

Here is where it gets really get confusing, though. On a Nexus (or Droid, for that matter), an image that is 300px wide will span the entire width of the screen. The result is a 300px image filling a space with considerably more pixels and you get a nasty upsampling effect (for lack of a better term). My layouts were rectified but my images on the high density screens just didn’t look good.

Luckily, the webkit image sizing engine came to the rescue. In the past (and on desktop browsers), if you rendered an image on-page smaller than it’s native size you’d see be able to tell. Images would get pixelated during downsampling. Not so on mobile devices. So for post images, for example, I call up a slightly larger image than I need and then downsize it right in-page (just using the width and height properties on the img tag). On the high resolution devices the result is a super crisp and properly sized image. I try to use this effect minimally though, on a page that lists a bunch of post thumbnails I just display an actual thumbnail at native size (the negative effect is less obvious on smaller images).

I’m sure calling up slightly larger images (less than 200px larger) will increase load times a tiny bit but I couldn’t live with launching a fresh new mobile site and having muddled images on the high res devices. And with ever-increasing network speeds I hope in the future it becomes even less of an issue.

Now we build

That’s basically it. Once you’ve got your conditional check in place and your viewport settings correct you can start the process of rebuilding all your templates on a mobile scale. Like I said, I put all my mobile templates within a single folder, /mobile. In the folder I’ve got any and all the files I need to make the mobile site tick (templates, images, scripts, etc).

To make a mobile page template (or archive template, for that matter), you simply open your current template and add the conditional at the top. Since a mobile layout tends to be much simpler, you can even cheat and use one mobile template to cover many desktop templates (on the mobile site I’ve got a single archive.php template that covers all my categories, tags, authors, etc, which I found much easier than creating a new template for each).

The thing to stress here is this isn’t some magical fix. We aren’t just changing a width here and there and calling it a mobile site. This is a ground-up rebuild that is creating new templates for mobile use. It’s a labor-intensive process but the result is more than worth it.

Bonus points

Along with making your layouts mobile-ready, there are numerous other tweaks you can make to enhance your mobile presence. In the header you can add a link to an apple-touch-icon (which will also be recognized by Android). When a user bookmarks the site and adds the link to the home screen, he will be presented with your custom icon.

<link rel="apple-touch-icon-precomposed" href="<?php bloginfo('template_url') ?>/mobile/images/home_icon.png" />

Setting an icon lets your site have a very specific and branded look on a user’s home screen. Icon are usually sized at 48×48 but again you can use a large image for a crisper result. Even Google does this, some of their icons are 57×57.

Another good practice is using minimal javascript touches to add native-looking functionality to your site. On the Android and Me mobile site I built a small menu that slides in and presents the user with navigation options (search, categories, etc). I’ve also done things like not display the comments by default, waiting to reveal them only when the user wants to see them.

The webkit engine also supports some new CSS properties I wasn’t accustomed to using at a production level. CSS3 makes it possible to generate drop shadows and gradients on the fly (whereas in the past you might have needed an image). Adding gradients is pretty easy and there are even online generators to make it even simpler. Using the new CSS properties at your disposal allows you to create a quicker loading and more dynamic layout (code changes are always easier than image changes).

So what’s next?

In addition to layout changes, there are some pieces of content that just don’t need to be displayed the same on the desktop and mobile site. One example are YouTube embeds. On the mobile site it displays a very large object that hangs way outside the viewport. To remedy the situation I’ve created a custom, mobile-aware shortcode. This allows our authors to add something like and the site will automatically spit out a full YouTube embed on the desktop site and a neatly formatted link to the video on the mobile site. I’ve also done the same with market downloads. On the desktop site you get a QR for scanning, on the mobile site you get a link for clicking.

I’ll be taking a look at WordPress shortcodes in a future article but I wanted to check with you guys to see if there are any mobile-specific questions you want discussed in a future tutorial. Anything you see on the current site you want explained? See something I’m doing that could be improved? Let me know!

PS: I’ll be speaking tonite at the Austin Android Users Group meetup. If you are in Austin and interested in Android, come on by!

Clark is a developer living in Austin, Texas. He runs ClarkLab, a small web firm with his wife, Angie. He's a big fan of usability, standards, and clean design.

    Most Tweeted This Week

  • http://frostygoodness.com Frosty Goodness

    Good article. From what I understand the “apple-touch-icon” only works on 2.x+ devices, since my MyTouch doesn’t show it.

    Have you ever tried allowing a file upload from a mobile site? I’ve been meaning to try it, but I’m not even sure the browsers allow it….

  • http://novemlife.com J. Millington

    Clark ftw

  • http://www.androidtapp.com AndroidTapp.com

    We’re using the Carrington Mobile plugin http://carringtontheme.com/ with some theme customization for our site. It works superbly but it was a pain setting up as every page component is buried in it’s own folder (i.e. header, footer, single, page, index, etc). Once you poke around and find out where everything lives, it gets easier to update.

    It would be interesting to try the native WordPress mobile theming solutions.

  • http://Website Brett

    Sorry for the off-topic comment, the post was great, but is that a plugin you’re using for the code snippets? I’ve been trying to find a good one. Could you let me know what you’re using? Thanks!

  • http://Website brett lewis

    Hmmm, theres an app for that. well, actually a plugin.

    but really, there are tons of plugins for that with detection for all types of devices, although, that iphone function is very appealing.

    • http://clarklab.net Clark Wimberly

      Any time you can avoid using a plugin it’s always a good idea.

  • http://www.bustersanimation.com

    I agree with everything you posted in this article, I’m a loyal follower so make sure you keep updating so frequently.

    • http://www.oeconomist.com/ Daniel [oeconomist.com]

      I see that you used a BBC photo of a guy in China ( &#10http://news.bbc.co.uk/2/shared/spl/hi/pop_ups/05/asia_pac_chinese_views_on_japan/html/6.stm ), though your IP number is from Indonesia. I smell oil and spiced ham; I guess that you must be … a spambot!

    • http://www.oeconomist.com/ Daniel [oeconomist.com]

      I see that you used a BBC photo of a guy in China ( hhttp://news.bbc.co.uk/2/shared/spl/hi/pop_ups/05/asia_pac_chinese_views_on_japan/html/6.stm&nbsp;), though your IP number is from Indonesia. I smell oil and spiced ham; I guess that you must be … a spambot!

  • Pingback: Posterous Update Q1 2010 // Blog.Tocki | Tilman Ockert, Stuttgart()

  • http://yurivolkov.com/Android/index_en.html Yuri Volkov

    Thanks for the article, Clark!
    There are still issues (things that need to be improved…) both with what is said in the article and with current design of this site (they are related, of course :-) ).
    Are these comments – the best place for discussion, and design of _this_ page – example of how the page for Android device should look?
    I mean, I want to start an open discussion/collaboration with you to improve both this tutorial and this site :-)

  • http://www.martindube.net Martin Dube

    Thanks for the article Clark.
    This is VERY usefull to me since I’m building my own theme using the WPML plugin. I’ll use WPtouch far a temporary fallback solution until I tweak my custom theme using your tutorial.

    Question about WordPress for iPad users…

    Since the main difference between iPhone & iPad is the viewport, do you know how we could target iPad’s users to adjust our layout for that bigger viewport ?
    Since the user experience (UX) is very diffrent between iPhones and iPads, the answer will be very useful for developpers.

  • http://www.iphonespyapps.com iPhone spy apps

    So far i’m not experiencing any problem with my IPhone yet. A top of the line SmartPhone that’s out in the market right now. Now Android emerged and put itself among the likes of IPhone. But still, i will pick IPhone than all the other SmartPhone that’s out now.

  • http://www.iphonespyphone.com iPhone Spy

    Hi, Congratulations to the site owner for this marvelous work you’ve done. It has lots of useful and interesting data.

  • http://Website Dave

    You should check out the Safari documentation on the viewport tag at http://developer.apple.com/safari/library/documentation/appleapplications/reference/safarihtmlref/articles/metatags.html.

    Your example viewport meta tag has at least a few issues. Values should be separated by commas instead of semicolons, and the user-scalable value should be “yes” or “no”.

    • http://clarklab.net Clark Wimberly

      Hmm, I sourced the viewport values from numerous other projects using it in the same manner, didn’t know there were various way to format. These values all still work, so I’m curious why the change is needed. Is it just a syntax thing or does these values actually fail somewhere?

      Thanks for the tip!

  • http://Website triavalay

    i have a four yr old female cat too she is very timid, she is afraid of her own shadow most of the time, but apart from when she was born (obviously) has never been around new born kittens, her and the mum get on really well but im just worried if she will be ok once the kittens arrive, i hope some one can advice me.

  • http://h deden


  • http://technology-sae.blogspot.com/ gunawan

    thanks very much for your info

  • http://www.modelingjobs.co.cc Pamela Scott

    And again, its for wordpress. I still trying to make my blogspot site looks nice in mobile phones. I really should consider switching to wp. Thanks anyway.


  • http://invisi-shield.com Sarah

    Hi there, i have put a link in the url box thingy (hope you can see it)www.invisi-shield.com. Just wondering if anyone has used this product b4 or knows someone that has as ive been savin for quite some time now and am about to invest in the new iphone 4. The problem i have is the last phone i had the screen ended up trashed because i can not seem to break the habit of sticking in my pocket with my keys or coins etc. If im going to spend a thousand dollars on the the coolest thing under the sun then i dont want this happening again. Ive researched this a bit and the invisibleSHIELD “sounds” like the best option but as you know its a bit hard to tell from little internet pictures so if anyone could please give me some advice on this it would be muchly appreciated. Great site by the way.

  • http://www.mobistealth.com Android Spy

    Congrats! You definitely done a great job. i appreciate your hard work and this amazing development.

    Thank you.

  • http://www.cellphonespysoft.com Name (required)

    WOW, great job !!! You must keep writing. I appreciate your effort and it is real informative.

    Well done !!!

    Thank you.

  • http://www.cellphonespysoft.com John Breganze

    Thank you dude for such a job you done to promote the word press. this will make the writes available on the go as well.

    Good Luck for next time as well !!!

  • http://jobvacancies-sae.blogspot.com/ gunawan

    thank you for the information,
    This was helped,
    spirit! ! ! ! !

  • http://Website Michael

    Thanks for the interesting article!

    However, setting the viewport ” user-scalable=0″ (or no) does not seem to have any effect on my HTC Desire (with Android 2.2). I still can scale the page.


    • http://none ChrisCicc


      “Thanks for the interesting article!

      However, setting the viewport ” user-scalable=0″ (or no) does not seem to have any effect on my HTC Desire (with Android 2.2). I still can scale the page.”

      This seems to be an issue with ALL HTC devices.

  • Pingback: New to Android and Me: Favorites | Android Application [dot] us()

  • Pingback: Popular JS framework jQuery coming to Android « My Tech Zero()

  • http://upilandroid.com mumuCute

    i don’t understand php code, but i want my web, android and iphone friendly, any software or application or plugin to help ?.thanks

    • http://www.oeconomist.com/ Daniel [oeconomist.com]


  • http://www.androidspyphone.net Android Spy

    Making blogs cell phone friendly is very important! Most bloggers dont realize what a spike in traffic they can get if they just take the time it takes to update their blogs.

  • http://www.iphonespysoft.com iphone Spy

    iPhone Spy software are very hot in the market now a day but the question is which software to prefer?

  • http://www.iphonespysoft.com iPhone Spy

    iPhone spy software are very demanding now a day in the market. The question is which software to buy which will justify the cost?

    iphone spy

  • http://www.freecellphonespying.com Cell Phone Spying

    This place is very popular for spy software huh. Take a look at this cell phone spyware.

  • http://Website скоростьu

    номер ICQ 602110стотридцатьодин Как купить ешки , таблы увро синтез мдма ,мдма , Якутск Владивосток Комсомольск-на-Амуре , Купить таблетки , Кисловодск , exstezy , Сыктывкар Находка Камышин .Купить зеленые таблетки , Псков Электросталь Ачинск , таблетки птички , Нижний Тагил Калининград ,
    Осуществляем доставку – курьером .
    Продаем метамфитамин первитин ,мдма , травка , бошки в городах: Пермь Ростов-на-Дону Москва Новосибирск Омск , как купить таблы мерседес , винт в Тула ,Вологда Курск ,Братск .
    Где приобрести Exstasy , фен ,таблы колеса ,тра­Ð²Ð° , таблы в городах: Краснодар Тюмень Тольятти Владивосток Хабаровск .
    Продажа осуществляется без встречи.
    Пишите можно в offline номер ICQ 6О211O131
    Где купить ЕКСТЕЗИ , Чкаловск Струнино , экстази спиды , Димитровград ,амфетамин гандж Где купить марихуана , Брянск Тверь Как купить таблетки колбасные таблетки супермен Вилюйск , барбитураты , exstazy Королёв , Купить амфетамин , Кострома Где купить mdma exstasy Махачкала Томск Набережные Челны ,марихуана , кокаина в Киселёвск , Купить таблы смайлы таблы шрек , Сусуман

  • http://www.whatismycomputerip.com/ wimcip

    Thanks a lot for yet another super article. I am always trying to find good articles. Thanks for creating this article. It’s just what I was trying to find. Truly wonderful post.

  • http://www.optastroclub.com astro club

    Thanks for making the trustworthy effort to discuss this. I feel very sturdy approximately it and want to read more. If it’s OK, as you achieve extra in depth wisdom, could you thoughts including extra articles very similar to this one with additional information? It could be extremely helpful and helpful for me and my friends.

  • http://www.toptanmallar.net Toptan mallar

    “Thanks for the interesting article!

  • Pingback: Tutto su mobile — Studio404 Web Agency()

  • http://www.spyingcellphone-review.com spying cell phone

    Thanks for the information, its very informative and also useful.

  • http://www.spyingcellphone-review.com Adams2368

    The article was very informative about how to create a mobile site using wordpress spying cell phone very good post.

  • http://androidofficial.com Name (required)

    iPhone vs. Android lol

  • http://www.androidspywareapps.net/ android spy software

    WOW! It will help a lot of people which is so kind of you. Thanks for all of your hard work!

  • http://www.oeconomist.com/ Daniel [oeconomist.com]

    The Apple Touch icon standard was originally for 57×57 icons; it has since been extended (with a SIZES attribute in the tag) to provide for 72×72 (iPad) and 114×114 (hi-res iPhone). Apple.com itself uses a 129×129 icon, so non-conformance evidently isn’t that big of a deal, but using a smaller non-conforming icon (such as 48×48) is just not a good idea.

  • http://www.kacaudah.com Valentin Battuello

    I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% sure. Any tips or advice would be greatly appreciated. Kudos

  • http://Website BravaBra

    Hello! it is little spam!
    I love your blog!

  • http://Website master

    Админу Мое приветствие Хочу предложить вам сотрудничество. Не нашел ваш почтовый ящик – написал бы туда. Ð’ чем заключается сотрудничество? Давайте обсудим это через почту или напишите свой номер аськи – я свяжусь тогда с вами. Спасибо за внимание :)

  • http://Website daypefalp

    Есть вопрос, а сайт популярный? Недавно здесь:вот интересно. Спасибо!

  • http://www.maroon5.com/member/74474/ Marquis Beardmore

    Believed invoking, and I will have to think about this more.. bookmarked. Hope to observe an revise soon!

  • http://www.myhtc.biz/blog myhtc.biz

    Nice Guide :) Can also be done using plugins when using wordpress but you dont get this sort of layout

  • http://Website LebedevAI

    Добрый день, наша компания занимается комплексной раскруткой
    сайтов и продвижением их в поисковых системах. Делаем качественный прогон по каталогам,
    профилям, форумам, доскам объвлений. У нас низкие цены, в нашей команде работают только
    профессионалы. Более подробная информация на сайте регистрация в каталогах
    Заходите на наш сайт. Заказывайте раскрутку сейчас ICQ 623605961 и Вам позавидуют конкуренты.
    Кроме того у нас вы можете скачете свежие версии программ для раскрутки Вашего сайта, базы для хрумер и аллсубмиттер и многое другое.

  • http://Website keylogger mac

    I consider, that you

    commit an error. I suggest it to discuss.

  • http://Website Name (required)

    I live in Edinburgh, Scotland and was unsure of ordering from over seas/online. It was the best thing I could have done! I recieved my dress about 11 days after ordering. I had some trouble with DHL – the delivering service used – but that isn’t Light In The Boxs fault. The dress was packaged very well and also turned inside out whih I thought was an excelent idea. Across the bust and over the shoulders and also the caped sleeves is padded so no need for a bra! The detail of the lace and pearls is amazing and looks just like the picture. The train is beautiful and the edging of it is enforced so it sits perfectly all the time. I am a size 12/10 in UK sizes so orderd the US size 8. It is a little tight across the back but I have 4 weeks before the big day so I will just watch what I eat and not over do it! It also came with extra beads and pearls in a little bag in case any fall off. I have noticed that a few have since fallen off, not a huge amount though, four or five beads. It came with a pink dress bag too which I am very greatful for. The white colour is lovely and I cannot wait to wear this dress for my big day. Thank you so much dressessales.com, I am a bride-to-be-on-a-budget but I feel like a princess…http://www.likadress.com

  • http://www.iphonespy.co/ iPhone Spy

    weldone, good job.

  • http://Website fara74

    Для всех граждан РФ.

  • http://soccertime.ru/ SoccerTime

    Доброго времени суток
    Посмотрите наш новый футбольный портал http://www.soccertime.ru.
    На портале вы сможете прочитать футбольные новости, информацию о стадионах и игроках.

  • http://www.androidfreeapp.net android free app

    excellent informations. i`ll try it on my website. thank you

  • BadBoyFromTheRai

    Давно эта тема не поднималась)
    Смотрю народ оживился

  • Pingback: 26 Great Tutorials To Make Your Website Mobile Friendly | JustWordPress.net()

  • Pingback: Mobile Toollbox for Wordpress (Tutorials, Plugins and Themes)()

  • Mudasir

    Great tuts. I love them, i have already done too much with wordpress, the thing that i have learnt from you is the way you do.
    I have also written some tutorials on WordPress Tutorials here.

  • MK

    Hey, I’ve used this app on Android called SecQ.me and it keeps track on other people on Gmaps. How do we do that?

  • Sobbytimb

    Внешняя красота изделий обеспечивается облицовкой их строганным шпоном, который фабрика производит самостоятельно

  • SymbianAndroid

    can i convert my wordpress blog http://symbianandroid.com/ to android or iphone compatible. Can you check the theme and reply please?

  • Pingback: WordPress Mobil Tema ve Eklentileri | Sanal Keyf()

  • Pingback: Risorse, tutorial, tool, framework e Wordpress per Mobile | Flashmotus()

  • Pingback: Tutorials for Making Your Website Mobile Friendly - noupe()

  • kavdofo

    yeah, that was quite useful. I was searching on google and also got a guy who build custom android app for wordpress

    here is link, http://www.peopleperhour.com/hourlie/develop-custom-android-application-for-wordpress-website-blog/59600

    may help someone who is looking their app custom made.

  • Paranthaman

    Thanks for your thought full article and i must work on this to make my mobile spy software related blog android and iphone friendly so that i can get more and more users easily.

    With regards
    play android games on pc

  • sginteractive

    I read your blog very Interesting and such a nice information. Thanks for sharing this useful information..

  • Vinny

    In today’s time, it is very essential to make website or blog user friendly. So best option is to create it according to every device or gadget. Nice info

    Nail Art Designs

  • Phedras

    The wp-touch is an excellent plugin which provides essential features for promoting post!

    Bob Hairstyles
    Long Women Hairstyles