AJAX + WordPress, made easy

One of the main reasons I redesigned my site – beyond the obvious facelift – was to give it a much needed new backend.  Everything is now powered by WordPress, which is awesome for control and simplicity, but isn’t exactly known for its AJAX prowess.

As a theme developer, I have been using a little technique to AJAX-ify WordPress themes for a while.  In the page template, you can use PHP to find out how the page was requested — was it an AJAX request, or was it a traditional page request? :

$isXHR = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest"));

Then, with a few conditionals, you can customize your template so things like the header (get_header()), footer (get_footer()), and sidebar (you guessed it, get_sidebar()) get left out of the page request if it was an AJAX request.

For example:

if (!$isXHR) get_header();

This is a clean and efficient way of serving up just the page content without the headers, footers, and whatever other content you want to omit from the AJAX request.  Less content = smaller file size = faster load time = less waiting for your visitors.

See it in action in the individual photo pages of my portfolio.