Google Gears Caching of WordPress in PHP

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

I was instantly fascinated by Google Gears so I had to immediately try out the sample code that you can download. The tutorial on the website gives a simple example of how to cache a few files using the Resource Store. It makes it very easy to setup a JSON manifest file that contains which pages you want to have cached. Here is an example manifest.

{
	"betaManifestVersion": 1,
	"version": "my_version_string5",
	"entries": [
	{ "url": "offline.js"},      
	{ "url": "test.php"},      
	{ "url": "test.php?page=1"},      
	]
}

What I thought I would then do was try and cache my blog using Google Gears. This required me to generate a manifest file with the URL’s that make up the blog. The first step was to perform a database request to get all the published pages and the static pages. The code below is very simplistic it reads in row by row and then generates the permalink for each one.

  function getlinks()
  {
     global $wpdb, $wp_version;
 
     $urls = array('http://blog.assembleron.com/');
     $limit = 100;
     $postRes = $wpdb->get_results("SELECT `ID` ,`post_modified`, `post_date`, 
     `post_status` FROM `" . $wpdb->posts . "` WHERE post_status = 'publish' OR 
      post_status='static' ORDER BY post_modified DESC LIMIT ".$limit);
     if($postRes) {
          foreach($postRes as $post) {                
              $urls[] = get_permalink($post->ID);
          }
      }
      return $urls;        
  }

We then build the manifest by calling the ‘getlinks’ method we have just described then outputting it in the JSON format.

  function buildManifest()
  {
      $urls = getlinks();
      $version = 'wp_ver_'.time();
      ?>
      {
        "betaManifestVersion": 1,
        "version": "<?php echo $version; ?>",
        "entries": [
        <?php
              $last = end($urls);
              foreach($urls as $url) { ?>
            { "url": "<?php echo $url; ?>"}<?php 
              if($url != $last) {
                  echo ',';
              }
              echo "\n";                
            }
            ?>
          ]
      }
      <?php                
  }

The other chunk of code I wanted to share was a quick alteration to the sample code. The default behaviour of the Resource Store is to fetch all the URL’s in the background allowing you to continue browsing while it does it work. This is fantastic but I wanted the user to know when all the pages had been fetched. In the code below I have made changes to check the status of the store. The Google API documentation has the following status values.

  • 0 - UPDATE_OK: An update task is not running. The last update task to run succeeded.
  • 1 - UPDATE_CHECKING: Checking for a new manifest file.
  • 2 - UPDATE_DOWNLOADING: Downloading the resources listed in a new manifest flie.
  • 3 - UPDATE_FAIL: An update task is not running. The last update task to run failed, and the error message is in

You can see from these values it is possible to see when a task is currently running/downloading and when it has finished fetching all the pages it needs. The code below just sets up a simple timer and checks every half second to see if the status has changed.

function createStore() {
  if (!window.google || !google.gears) {
    alert("You must install Google Gears first.");
    return;
  }
  store.manifestUrl = MANIFEST_FILENAME;
  store.checkForUpdate();
 
  var timerId = window.setInterval(function() {
    if(store.updateStatus == 2) {
    textOut("Downloading...");
    }
 
    if (store.currentVersion && store.updateStatus == 0) {
      window.clearInterval(timerId);
      textOut("The blog is now available offline.\n");
    } else if (store.updateStatus == 3) {
      textOut("Error: " + store.lastErrorMessage);
    }
  }, 500);  
}

Restrictions:
Because the code only generates a manifest with the URL’s from the permalinks it does mean that only direct links to those posts work. Attempts to navigate using tags or any other navigational links do not work and require you to go online.

If you want to try the system out click on ‘offline’ in the menu bar. It will ask you to download the Google Gears application first then you can try it out. If I get too much traffic I will have to disable it as it performs 100+ requests. UPDATE: I have for the minute removed the demo page due to excessive traffic.

This really is just a quick hack together to see what is possible in a short space of time. I will tidy things up over the next couple of days and release the code so others can use it.

The Future
This is probably just the beginning for Google but I can already see massive potential just for what they have released so far. I can imagine that a large number of the common frameworks out there will be adding in support as quickly as they can (Cake, Zend, Symphony, drupal, mambo, etc..). Although only certain kinds of websites will be able to make use of this technology (to start with) I think it is going to have pretty rapid uptake even if this just starts out as companies having their contacts pages stored for offline so that you can view them when you need them! (i.e. when your on the road and you suddenly realise you didnt print out the address.)

There Are 20 Responses So Far. »

  1. Thanks :D

  2. […] Nick Halstead escribio en su blog un ejemplo de como “cachear” Wordpress, muy interesante artículo. […]

  3. WOW NICK!

    Awesome. I love it.

    Thanks for taking the time to do this. I was equally impressed with the release of Google Gears this week but didn’t have any time to actually work on anything. Nicely done, Nick!

    Just in case you or anyone else is interested, there’s a guy called Rusty who also did a very nice job taking Google Gears out for a test spin. You can read his tutorial with step-by-step instructions at: http://www.seroundtable.com/archives/013657.html

    (Hey, I’m just trying to help to spread the word about Google Gears to those who are interested . . . I’m not getting paid or anything to promote this kick-tush technology.)

    Thanks again,

    WebGyver
    ————————————————————
    Making web stuff out of bubble gum and kitchen chemicals.
    http://www.webgyver.info

  4. […] developers are working on solutions to put this new functionality into practice. Nick Halstead has created his own handy little script to help with caching WordPress content. I was instantly fascinated by Google […]

  5. Thanks for the support WebGyver and for the link. I will hopefully do something a little more complex with Gears in the future. The SQLlite integration interests me the most so it has to be something that leverages that. Just need to have a bit of a brainwave of what to do with it.

  6. […] Google Gears Caching of WordPress in PHP Related PostsAdd fancy alias for your localhost or 127.0.0.1A few student in my class ask me how to change default address for testing php script from http://lo…Google Blog SearchI like read blog, very interesting to see someone posting “unique” approach to solve their spesific …Google Maps for My VillageI used to use maps only in Geography lesson While visiting my village and see interesting view, our …Step by step to get your own email in google appsMy friend in USA  ask me how to get email from google apps. I pointing him to my post at wordpress.c…tada mono yasui mono wa nai, free is the bestWow, amazing post from John Chow I just trying to find dynamips idle-pc value experiment until my…Popularity: 3% [?]Share This […]

  7. WordPress and Google Gears…

    And, here we go! Here’s a tutorial on how to cache a WordPress blog for off-line reading using the Google Resource Store.

  8. Google Gears (up!)…

    Google launched Gears this weekend - very very sexy technology-wise.
    This could herald a lot of interesting application development, particularly for product that are required to work on and off line.
    I came across the news via the Google blog, but al…

  9. Pretty cool Nick. I just finished up a (very beta) WordPress plugin that lets users cache your blog with Google Gears. It’s pretty similar to your code, but it auto-generates a new manifest when a change is made, and it also caches static resources under wp-content. I think there’s some real potential here…

    You can check out my post @ http://immike.net/blog/2007/06/04/wordpress-plugin-wp-offline/

  10. […] Google Gears Caching of WordPress in PHP Bookmark and share: These icons link to social bookmarking sites where readers can share and […]

  11. Very nice work Mike! Sounds like you have been very hard at work since Gears launched. I will make sure I include your article in my next developer link post (you just missed last nights one.)

  12. […] - und ich bin wieder erstaunt, wie einfach etwas zunächst sein kann. Mit der Anregung von Nick Halstead sind die aktuellsten 20 Seiten dieser Seite nun “geared up“. Was jetzt fehlt sind die […]

  13. […] Halstead has a post titled Google Gears Caching of WordPress in PHP, which shows how you can effectively use it to cache your […]

  14. […] offline technology. Google makes it easy with excellent tutorial, if that is not enough there are more examples already floating […]

  15. […] The Programming and Management Blog » Google Gears Caching of WordPress in PHP (tags: google JavaScript PHP gears) […]

  16. It is nice article! Thanks, good info!

  17. Amy Reid Full Porn Download Free…

    Amy Reid Full Porn Download Free…

  18. Black Teen On White Dick…

    Black Teen On White Dick…

  19. This is very useful Thanks.

  20. Very helpful, Many thanks!

Post a Response