Flying memes

WiPad 0.3, aka: how to handle permalinks

I’ve just committed the 0.3 version of WiPad, this new release introduce a new mechanism which helps handle permalinks. Having to deal with a single-file Sencha-based application made me pretty hard to figure out how to re-introduce permalink and give the opportunity to reach a single post using its url.


The strategy I adopted was to use the ‘window.location.hash’ in order to detect which post to display. So when a browser tries to solve a post url it gets redirected to the index page with a special anchor that tell the main application which post has to be loaded first.

Here’s the part that handle this ‘anchor recognition’ in the main application:

onReady: function() {
  if (window.location.hash == ''){
    wipad.Main.init();
  }else{
    Ext.Ajax.request({
       // Here I call single.php simulating a single post navigation
        url: "<?php echo get_bloginfo('wpurl')?>" + window.location.hash.substring(1),
        success: function(response) {
          item_array = eval(response.responseText);
          wipad.Main.init((item_array[0]=="") ? null : item_array[0], item_array[1]);
        }
    });
  }
}

And here’s how I wrote single.php in order to handle both redirect and post rendering:

<?php
 // determine if we're answering an AJAX call or NO
 global $is_ajax; $is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']);

// if we're answering an Ajax call this means we need to render back the requested post
 if($is_ajax){
   the_post();
   $the_content = json_encode("<div class='x-htmlcontent the_content'>".apply_filters('the_content',get_the_content())."</div>");
   $the_title   = json_encode(get_the_title());
   echo "[".$the_title.", ".$the_content."]";
   exit(0);
 }

 // Otherwise redirect to the mail app with the anchor setted
 header('Location: '.str_replace(get_bloginfo('wpurl')."/", get_bloginfo('wpurl')."/#/", get_permalink()));
?>

Hope this may be useful to someone trying to figure out how to deal permalink related problems.

Tags: , ,