I have a custom tag-search feature, which allows people to search multiple tags to return relevant posts. Say they want to see posts that are tagged both 'Wordpress' and 'Tutorials'. I'm using the template_include filter, like so:
public static function template_redirect( $template ) {
if( isset($_GET['tag-search']) )
{
$template = locate_template( array(
'search.php',
'archive.php',
'index.php'
));
}
return $template;
}
the tag-search variable holds the name of the taxonomy, I check if it is set, thus indicating a search is being performed.
At this point template resolves to search.php, like it should. So that's good.
In the pre_get_posts action I add a tax_query to modify the returned posts to just the selected tags, and I set is_search to true, and is_home to false. Here is my pre_get_posts action:
public static function pre_get_posts($query) {
if( !isset($_GET['tag-search']) || !isset($_GET['terms']) ) return $query;
if( strtolower( $_GET['method'] ) == 'and' )
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms']),
'operator' => 'AND'
)
) );
}
else
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms'])
)
) );
}
$query->is_search = true;
$query->is_home = false;
return $query;
}
However, when I perform the search, the body class is 'home', and all of the is_home and is_front_page conditionals are true, which they shouldn't be, cause I just specifically stated I want this to be a search template right?
I know this can be done - when I add &s to the query string it works as it should - though it's a bit ugly that way. Any insights?
Aucun commentaire:
Enregistrer un commentaire