Custom post archive with search, is_search() is false?

I have a custom post type, and have created an archive template, archive-custom_post_type.php, which includes a search form.

I am then using pre_get_posts to add parameters to the query to filter my results.

However, to make sure this only happens on this archive page, I want to check a few things. First I am checking if the post type matches.

But then I wanted to check the is_search() parameter, only to see that it is false.

How and when is this defined? Can I do anything to let WP know that a search is happening?

pre_get_posts callback

$post_type = get_query_var( 'post_type' );

if ( $post_type === 'document' ) {
    $params = $_POST;

    if ( $params ) {
        $query-set( 's', $params['keyword'] );
        $query-set( 'order', $params['order'] );
        $query-set( 'orderby', $params['order_by'] );
    }
}

archive-document.php

?php get_header(); ?

?php get_template_part( 'my-slug', 'document-filter' ); ?

div id="search-results"

?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?

    div
        ?php the_title(); ?
    /div

?php endwhile; else : ?
    pSorry, no posts matched your criteria/p
?php endif; ?

/div

?php get_footer(); ?

document-filter.php

form id="document-filter" method="post"
    select name="order_by"
        option value="date"Date/option
        option value="title"Name/option
    /select
    select name="order"
        option value="desc"DESC/option
        option value="asc"ASC/option
    /select
    input name="keyword" type="text" placeholder="Filter by keyword" value=""/
    input type="submit" /
/form

Topic wp-query custom-post-types Wordpress search

Category Web


Name your keyword input just s

<input name="s" type="text" placeholder="Filter by keyword" value=""/>

This is enough for WP to recognize the request as search plus you won't have to do the $query->set( 's', ... ) later

In pre_get_posts action use the conditional is_post_type_archive( 'document' ) so your if statement look something like this:

if ( is_post_type_archive('document') && is_search() ) {
  ...
}

Hope that helps

Update

Since you're searching, search template (search.php, index.php) will take precedence over the archive. You will need to filter the template which WP assigns for those requests as well.

add_filter( 'search_template', function ( $template ) {
  if ( is_post_type_archive('document') && is_search() ) {
    $find_template = locate_template( ['archive-document.php'] );

    if ( '' !== $find_template ) {
      $template = $find_template;
    }
  }

  return $template;
});

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.