WordPress using wrong template after AJAX loading

A tricky problem with my AJAX-search function. WordPress decided to use front-page.php for loading extra AJAX-content. The problem was that this styled the content in a different way than I needed.

After identifying the root of the problem (which takes time!), I looked around for a neat solution. What I came up with was overriding the template hierarchy in case the request URL contains a “?” (which means we are searching). This is not a universal solution but it works for me.

Add the following to your functions.php


function ccb_template_override($template)
{
if( strpos($_SERVER['REQUEST_URI'],"?")!==false )
{
return locate_template('search.php');
}
return $template;
}
add_filter('template_include', 'ccb_template_override');

For a better solution that applies to all AJAX-loaded content, we need to set a flag (for example a GET-variable in the AJAX-request, or depend on server variables that tell us whether a request is an AJAX-request or not (which I understood are not universal yet).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.