Using AJAX with WordPress

September 28th, 2011

There’s already lots of places to learn about AJAX, and probably lots of plugins for WordPress to enable AJAXy features. I’ve been working on adding some AJAX to bypuk.com‘s home page, to pull in summaries and links for different movies without interrupting the showreel video. I did it by customising the site’s template. The least documented part of the puzzle was getting plain HTML snippets and post lists from WordPress.

I created very simple template files that don’t even pull in header.php or footer.php. They just display a snippet of the post’s or page’s content, or a list of posts with a title, thumbnail and snippet. Each piece was wrapped in classed divs for easy CSSing in the parent page.

I used WordPress’s template_include hook to hijack URLs to use these templates. I found this more reliable than the better documented template_redirect because you don’t steal control from WordPress then kill it. (I found the WordPress queries weren’t fully set up for the template file, and worried that preventing WordPress’s cleanup routines running could leak memory, leave database connections open or leave files open.) I think I found out about template_include here

I used URL query variables to override the template, so by adding ?content=summary to the URL for a page, my AJAX request would pull in just the title and a snippet of the content, rather than the whole page, with header etc.

Here’s the function I added to my theme, in functions.php, to override which template was used.

function byp_rewrite_template($template) {
  /* 
   * If the URL contains the content query variable (e.g. ends with
   * `?content=summary`) we use a special template to generate the page.
   * This is useful for AJAX calls in particular, where the page is very
   * plain, ready to be dropped in a DIV.
   */
  if ($_GET["content"] == "summary") {
    return (TEMPLATEPATH."/page_summary.php");
  }
  else if ($_GET["content"] == "moviesummary") {
    return (TEMPLATEPATH."/page_moviesummary.php");
  }
  else if ($_GET["content"] == "posts") {
    return (TEMPLATEPATH."/page_posts.php");
  }
  return $template;
}
add_action('template_include', 'byp_rewrite_template');

The function is given the template that WordPress has chosen, and returns the template WordPress should use. The function above, looks at the URL variables and overwrites the template to use, if it recognises the value of content.

Finally, the template files themselves can look at other URL variables, so the AJAX call can specify, for example, how many posts to display.

Leave a Reply