How to create a mobile WordPress theme with jQuery Mobile

by Jean. 38 Comments -

Last month, jQuery Mobile was released. This tool allows you to easily create mobile websites and web apps. In this tutorial, I’ll show you how to create a mobile-optimized WordPress theme.

Here is what we’re going to build together today. Click the image to view the live demo.

Step 1: Getting files

We could have created our theme from scratch, but there’s no need to reinvent the wheel when there’s tools that can help you save lots of time. The tool we’re going to use is called Blank Theme. It is a functional WordPress theme, but without any styling. That way, it can be used as a starting point for creating your own themes. For example, I’ve used Blank Theme to create the current Cats Who Code theme.

Blank Theme has been created by Chris Coyier and it can be downloaded here. Get a copy and unzip it on your server or hard drive: We’re going to start. Optionally, open the style.css file and modify the theme name to fit your own needs.

Step 2: Header and Footer files

As we’re going to create a theme that will rely much on jQuery, the first thing we have to do is to link to jQuery and the jQuery Mobile files. You can either download the files individually and link them to the theme, or you can use jQuery’s CDN and link the online versions to your theme. I personally prefer linking to the online version, but it’s up to you.

Open the header.php file from the Blank Theme directory, and insert the following code to link to jQuery Mobile, within the <head> and </head> tags:

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>

Once done, the required jQuery files are now linked to our theme. But we’re not done yet with header.php. As jQuery Mobile uses HTML5, we have to modify the doctype. Replace the first 6 lines of the file with:

<!DOCTYPE html>
<html>
<head>

Then, scroll down to the bottom of the file and locate the <body> tag. Replace everything from the <body> tag until the end of the file by the following:

<body <?php body_class(); ?>>
    <div data-role="page" data-theme="b" id="jqm-home">
        <div data-role="header">
            <h1><?php bloginfo('name'); ?></h1>
	</div>

        <div data-role="content">

We just dove in jQuery Mobile with the code above. What? We haven’t even wrote a single line of JavaScript! That’s right. jQuery Mobile doesn’t need you to write any JavaScript. All it needs is some <div> tags with the proper data-role attribute.

As an explanation, take a look at line 3 of the code above. Have you noticed the data-role="header"? It describe a header bar. If you save the file and view your theme right now, you’ll notice a header bar on the top of the screen, with your blog name.

Now, save header.php and open footer.php. Replace its content by:

        </div><!-- data role content-->

        <div data-role="footer" class="ui-bar">
            <a href="#jqm-home" data-role="button" data-icon="arrow-u">Up</a></div>
        <?php wp_footer(); ?>
    </div><!-- data role content-->
</body>

This simple code will insert a footer bar to our theme, with a button that will scroll up to the header when the user will tap on it. Did you noticed the data-icon attribute? It allows you to specify which kind of icon you want. In our case, we want an up arrow, but there’s lots of different icons you can use.

Step 3: The homepage

Now, let’s code our homepage. As we’re building a theme for mobile devices, we do not need anything fancy. Let’s build a list of our recent posts. To do so, open the index.php file, locate the loop, and replace it by the following code:

<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile;endif ?>
</ul>
<?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>

Save the file and take a look to your theme: It looks great! We now have a list of posts on our homepage. Once again, we have a very good looking list, with some nice transition effects, without coding a single line of JavaScript. That’s the magic of jQuery mobile.

The list is created by using the data-role="listview" attribute on the unordered list. The other attributes specifies the appearance of the list. Want to experiment a bit? Simply replace data-theme="c" by data-theme="b" and see what happens.

Now, modify the loops of the search.php and archive.php files like we did with index.php.

Step 4: Post and pages files

By default, the single.php and page.php files from the Blank Theme looks good in our mobile version, so we do not need to modify those files. Though, we can do something to enhance user experience: Mask the comments by default, and show them only if the user decides to. This can be done extremely easily using jQuery mobile.

Open comments.php and locate line 15. Insert the following line:

<div data-role="collapsible" data-state="collapsed">

Then, go to line 31 and insert a closing </div> just before the else statement. Save the file and have a look at one of your posts: Comments are now masked by default, and a tap/click on the bar display them. If you prefer to show the comments by default, no problem: simply remove the data-state="collapsed" attribute. That’s all we need to create a collapsible content block.

Did you noticed that on posts, the header bar is showing a “Back” button? A click/tap on it will take you back to your blog homepage.

Step 5: Implementing search

Right now, we have a theme fully optimized for mobile devices. But it is missing something important: An easy to access search bar. Open your searchform.php file and replace its content by the following:

<form action="<?php bloginfo('siteurl'); ?>" id="searchform" method="get">
    <div data-role="fieldcontain">
	    <input type="search" name="s" id="search" value="" />
	</div>
</form>

After you saved the file, reopen index.php and include the search form between the get_header() function and the unordered list which contain our posts:

<?php include('searchform.php'); ?>

Our homepage now has a working search form. Right now, our theme is done and we can use it on a production site.

Step 6: Final touches

Of course, even if the theme we’ve built is perfectly functional, there are still a lot of things that can be done to enhance its look and functionality. For example, I have noticed that the search field is smaller than the list items. In order to make the search field as wide as the list items, paste the following in style.css:

.ui-input-search{
    width:96% !important;
}

That’s all for today. I hope you enjoyed this tutorial. If you want to download the finished theme, just click here.

Also, I just redesigned my other blog Cats Who Blog so don’t hesitate to visit it or grab the RSS feed to read it later. The blog is now 100% focused on tools to make your life as a blogger, developer or designer easier. Enjoy!

  • http://www.tomhermans.com Tom Hermans

    Haha, purrrfect timing Jean-Baptiste !

    Have just started working on this myself too, small app already working, now looking into a full fledged customized theme with all options.

    Am definitely gonna read this one in detail ! Thx!

    ToM.

  • Jeroen

    You could also use the WordPress plugin WPtouch:
    http://wordpress.org/extend/plugins/wptouch/
    This does everything for you (I think, I don’t use it at the moment).

  • http://skattertech.com SK

    Hey Jean,
    I designed a fairly elegant WP Mobile optimized theme to complement the standard site.

    I was wondering if you had any suggestions on how to handle automatically redirecting user-agents matching iOS, Android, webOS, etc to the mobile site.

    I found some PHP plugins to do that, but here’s the catch. I also want to give users the option to click a button and switch back to desktop easily. For instance, if they have an iPad, they might just want to use the regular site.

    I would appreciate any advice! thanks!

  • http://www.emotionstudios.net Mihai

    I’m not a developer but you make it sound so easy. Very nice.

  • http://sideradesign.com paul

    interesting, so what would be the advantage of this compared to using media queries?
    can you load the mobile theme automatically by detecting the device?

    • Khalid

      Creating a mobile theme has one important advantage: you can keep your code clean and made it faster (which is quite important for mobile-optimised websites). How? Well, less important stuff, like banners, lists of most viewed posts, lists of most commented posts, etc. are not even in the html-file. If you would use media queries you would use in your css-file div {display: none;}, but all this ‘unnecessary code’ (for the mobile site) will still load in your html-file and make your site slower.

      If you want to redirect mobile users to a mobile theme, you can use a plugin.

  • http://vinaganda.com Fred

    You really did a great job. Thanks for that.

    Just for info: If you are struggling to get the post thumb in the list. You need add the fonction in functions.php

    :P

    • http://www.designisnowhere.com/ Paulchen

      Could you explain me how? :)

      And to all:
      Is there any way to use this theme next to my normal theme and just show it to visitors from iOS? :)

      • http://vinaganda.com Fred

        I just added:

        /*Post Thumb*/
        if ( function_exists( ‘add_theme_support’ ) )
        add_theme_support( ‘post-thumbnails’ );

        And putt in the index.php:

        <a href="”>

        But we need take in consideration that the development stage is in Alpha, even when I visting the jquery site with my ipad i got some bugs in the page load. But better to start working on it now :P

  • http://nighto.net/ Nighto

    Nice guide, thanks!

    Here, the back links are not working; i suspect because of WP writes full absolute links instead of relative links. Any idea?

    Cheers

  • Pingback: JQuery Mobile Based WordPress Themes – WP Mobile Press

  • http://13strokes.com Shibi Kannan

    Check out this forum post at

    http://forum.jquery.com/topic/back-button-support

    The back button has some issues in certain devices.

    To hide it, add data-nobackbtn=”true” to the header div.

  • http://www.takethetunnel.com Andy Holiday

    Oh Great another load of tools to get used to! I think we really need the mobile aps/code though. I’m seeing more and more people using mobile devices to access my site.

  • http://k-win.fr kevin

    Just tried the whole theme and when i hit the back to top button it hides the whole site. Anyone has seen this? Am testing it locally with Chrome/FF/Opera/Safari, does the same.

    • http://www.carolinalorca.cl carolina lorca

      actually, that is what happened to me too … infact, after i made the changes in header, then footer, and finally in index.php … wordpress goes blank :S
      need some help here

  • http://www.dcmedia-design.com DANIELLE

    Awesome tutorial, thank you so much for this. It’s so true not to invent the wheel when you don’t have to!

    I’ve been researching about getting into mobile websites, and I think JQuery is the way to go when making it iPhone “friendly”.

    So thank you again!

  • http://www.exatta.ind.br Lucas

    Just for info: If you are struggling to get the post thumb in the list. You need add the fonction in functions.php

  • http://www.uniquetipsonline.com Madav

    Thanks for the unique tips.How can I customize the thumb size ?

  • http://www.ChiefAlchemist.com Mark “Chief Alchemist” Simchock

    Great, thank you!

    Does anyone know how to run a non-mobile and mobile site off the same WP back end? That is, same content to pull from but two different presentations.

    I can do mysite.com and mysite.com/mobile or mysite.com and mysite.mobi. I understand there might be some tradeoffs with SEO, etc. but I believe making the functionality available to users is more important than Google :)

    Anybody?

    • Martin Scott

      It is possible to do this. One way would be to use a theme switching plug in (such as nkthemes). You could then place a mobile icon with a coded link to the mobile theme, rather than using the widget in a sidebar.

      I am currently experimenting with this.

      • http://www.ChiefAlchemist.com Chief Alchemist

        Hey Martin – So essentially you’re just flip-flopping two themes back n forth on a user by user basis? Interesting :) I guess that could work.

        But that could definitely cause some SEO issues since it sounds to me like a given URL could have two sets of content associated with it, eh? I was kinda hoping for a slightly cleaner break between the two sites.

        That said, I’ve been doing some work with Headway and I’m considering defining a page (say) /Mobile and then just make all the children pages of that page the smartphone site.

        Unfortunately, I haven’t had the time to experiment like you have :) Please keep me in the loop. I want to get to this soon for a project that’s about to move forward. Thx.

        • Sam MaPro

          Hey Chief – did you ever figure this out? I am working on a new site that I want to do exactly this. Same data; different view of site for mobile and desktop.

          Thx

  • Pingback: 3 free WordPress themes I’ve created for you - CatsWhoCode.com

  • http://www.newmobiles.co.in Rahul

    I am completely satisfied with Jeroen commented at 2nd position, but yes here i would like to say that we are going to implement this.

  • Pingback: 8 awesome new jQuery plugins to have in your toolbox - CatsWhoCode.com

  • http://netlumination.com/ Peter Ajtai

    Nice article. I’m working on making a mobile version for my site now, and this’ll be helpful.

    It’d probably be better to use wp-enqueue-script ( http://codex.wordpress.org/Function_Reference/wp_enqueue_script ). WP already ships with regular jQuery, so it gets updated automatically with WP and you don’t have to worry about updating the jQuery version manually. Also, enqueue_scripts guarantees you only load each script once.

  • idenv

    Looks and works great! Can anyone help me with loading post images? I can only find showing images loaded as attachments but i’m looking for showing ‘normal’ images. I can find WordPress-snippets related to thumbnails and attachments. Can’t find the right information about normal images anywhere…

    Thanks in advance.

  • http://www.iknowtec.com Chris

    Now my question is: How do you keep the page in the center of the screen? How do you make it so that if they drag their finger left or right across the screen the page doesn’t move that way?

    • http://www.danhannigandesign.com Dan H.

      I think that has something to do with the viewport tag…

      • http://www.danhannigandesign.com Dan H.

        Sorry, it posted before I was done. Using something like this, in the appropriate context might work. Especially the “user-scalable=0″.

        meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;”

  • Dave

    Is there any way to share the wordpress database bewteen two installs of wordpress? if not how do you people get the content from the mainsite to the mobile site?

    Thanks

    Dave

  • Paul

    Hi there,

    First of all, thanks for the excellent tutorial on this. Really helps.

    I’m using both yours and the one at net.tutsplus.com (haven’t linked as it might be rude)… but I’m having minor difficulty in completing these tutorials. My main website features a parallax scrolling setup, with multiple pages on one page. I’ve noticed a few other mobile sites featuring a similar setup, but every time I do a tutorial like this it’s the page.php which is the front, and not index.php – I can’t actually find a way to setup page templates only applicable to mobiles.

    Any idea on how to do this?

    Thanks for your time.

  • Rajendra Prasad

    is it necessary to create a custom theme for creating a mobile wordpress site,only that WP-TOUCH plugin is enough for mobile site?
    already i have wordpress site,now i need to make a mobile site for it so,
    can any one tell me what are the files i need to create and change

  • http://FatWalr.us Luke

    This is great. I love JQuery and what it’s doing for the web. However, no matter how much I love the do-it-yourself approach, I can’t get past how easy plugins are to use. I use the WPTouch plugin and get really great functionality and it’s drop-dead easy to install and maintain. I just wrote a post about it with a bunch of screenshots for anyone interested: http://fatwalr.us/2012/02/mobilize-your-wordpress-blog/ But, lots of respect for those of you who take the JQuery route. The flexibility that you’ll have once it’s set up will be really great as well.

  • http://www.ZenOfWP.com Greg Turner

    As I understand it jQuery Mobile lets one create a single theme that will work for all kinds of devices. Except for one big glaring error. Many users of mobile devices have limited bandwidth. Therefore, in designing a theme that is optimized for such situations, you do not want to push out all the content of your site. Since jQuery Mobile works on the client side, this requirement is not met with this way of doing things.

    There are many areas where you still need to detect on the back-end whose is requesting a page. Perhaps you want to have different menus depending on the requesting device, or a different front page.

  • Theo

    Using the finished theme from this tutorial I notice that it becomes impossible to load the WordPress admin pages. Choosing any option from the admin toolbar results in a blanc page.

    Any suggestions about how this can be resolved would be greatly appreciated.

  • http://mwbzone.com Equilibrium3

    Hi

    The link to the blank theme has an update for a link to a html5 blank theme.
    Will that also work and is it recommended?

  • http://mobi007.com Terry Jett

    Very good tutorial! Thank you for sharing and give us more:)

    Use to avoid jQuery Mobile until I started digging in deeper, really quick way to build sites and apps.