Pages

Thursday, January 19, 2017

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).

0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Lady Gaga, Salman Khan