admin管理员组

文章数量:1310306

I'm trying to separate out different templates which utilise WordPress' search (s query var) along with different post types.

Situation 1: Default WordPress search page (search.php). Example: example?s=test

Situation 2: Post type archive (archive-{$post_type}.php), with search and taxonomy query var filtering ability. Example: example/questions?s=test&category=wordpress

Situation 2 has a few different final templates based on what post type is being queried.

So far I've managed to get the above to work with a function similar to this:

function wpse_redirect_search_page_post_types( $template ) {
    global $wp_query;

    if ( $wp_query->is_search ) {
        if ( get_query_var( 'post_type' ) === 'question' ) {
            return locate_template( 'archive-question.php' );
        }
    }
    return $template;
}
add_filter( 'template_include', 'wpse_redirect_search_page_post_types' );

However I encountered an issue when attempting to filter the search results page with different post types. I've got a bunch of checkboxes to filter what post types to show on the search results page, and the moment I've got only one post type (eg example?s=test&post_type=question) it sets the template to archive-question.php.

In terms of the $wp_query, they're identical (barring query hash differences) for
example?s=test&post_type=question
and
example/question?s=test&post_type=question.

What's the best way to do a check for whether I'm intending to show the search or archive template? The only other way I know how to do this is access the url through $_SERVER['REQUEST_URI'], but I was hoping there was a more WordPress-centric way of checking what template it intends to use.

Final use-case goals:

  • example/questions?s=test (archive)
  • example/questions (archive)
  • example/?s=test (search)
  • example/?s=test&post_type=question (search)
  • example/?s=test&post_type=question,answer (search)

本文标签: searchRedirect template based on permalink rather than wpquery