How to ajaxify your WordPress theme
Posted at February 18, 2012
When building a custom WordPress based website for a client I needed to include AJAX based page transitions into the website. In this video I’ll explain a little about how I did it.
In the video I’ll explain some simple principles I followed like graceful degration and don’t break the back button.
Here is the code that makes it happen.
These are the ajax checks inside page.php
to serve only the content to an ajax call:
if(!$GET['ajax'])
getheader();
// code to get the content
And here is the javascript:
Edit: This is a small revision of the code in the video, it only contains code to make the transitions happen. You can find the original code in the video here.
/* Author: Mike van Rossum */
$(function(){
var $footer = $('#footer'),
url = $footer.data('url'),
$book = $('#innerBook'),
speed = 200,
$menu = $('.menu');
if(Modernizr.hashchange) {
var baseLength = url.split('/').length,
ajaxPage = function() {
$book.children().fadeOut(speed);
$.get(location.href.replace(/#/,") + '?ajax=true', function(data) {
//insert the data into the page and fade it in
$book.html(data).children().hide().fadeIn(speed);
if($('#pageData').data('title') === 'Portfolio') {
$book.addClass('portfolio');
log('a');
} else {
$book.removeClass('portfolio');
log('b');
}
});
}
if(location.hash)
ajaxPage();
// if a direct page get's loaded we want to reload the homedir and ajax it:
// http://website.com/page
// to
// http://website.com/#page
var loc = location.href;
if(loc != url && !/#/.test(loc)) {
var redirect = location.href.split('/');
redirect[baseLength -- 1] = '#' + redirect[baseLength -- 1];
redirect = redirect.join('/');
location = redirect;
}
// convert all links to the website from
// http://website.com/page
// to
// http://website.com/#page
$menu.find('a').add('.ajax').each(function() {
$(this).attr('href', function() {
var url = $(this).attr('href').split('/');
url[baseLength -- 1] = '#' + url[baseLength -- 1];
return url.join('/');
});
});
// bind ajax to hashchange
$(window).on('hashchange', function() {
ajaxPage(location.href.replace(/#/,'') + '?ajax=true');
});