Customize Search to only search current custom post type

I have 3 custom post types and want the search widget to only search the custom post type it’s currently on. ie. If viewing cpt_1 (single or archive) and someone uses the search widget in the sidebar it should only return results of cpt_1. Similarly viewing cpt_2 and searching should only return cpt_2 results.

I tried this:

Read More
<?php
// functions.php 
function search_cpt1( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array( 'cpt1' ) );
    }
    return $query;
}   

function search_cpt2( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array( 'cpt2' ) );
    }
    return $query;
}   

if ( 'cpt1' == get_post_type() ) {
    add_filter( 'pre_get_posts', 'search_cpt1' );
}

if ( 'cpt2' == get_post_type() ) {
    add_filter( 'pre_get_posts', 'search_cpt2' );
}

?>

I’ve also tried this way without success:

<?php
function jc_search_cpts( $query ) {
    if (('cpt1' == get_post_type()) && ( $query->is_search )) {
            $query->set( 'post_type', array( 'cpt1' ));
    }
    if (('cpt2' == get_post_type()) && ( $query->is_search )) {
            $query->set( 'post_type', array( 'cpt2' ));
    }
    return $query;
}
add_filter( 'pre_get_posts', 'jc_search_cpts' );

Related posts

Leave a Reply

3 comments

  1. You will need to modify searchform.php file in your theme directory.

    To search for current post type posts add following code inside the form !

    $post_type = get_post_type();
    if($post_type){
        echo '<input type="hidden" name="post_type" value="'.$post_type.'" />';
    }
    
  2. You can also do it using a WordPress filter pre_get_posts. Add or remove the post types as you see fit.

    function es_search_filter($query)
    {
    
        if ($query->is_search && !is_admin()) {
            $query->set('post_type', ['pages', 'posts']);
        }
    
        return $query;
    }
    
    add_filter('pre_get_posts', 'es_search_filter');
    
  3. I was able to do this by creating a custom search form by adding this:

    <input type="hidden" name="post_type" value="attorney" />
    

    So, my search form looks like this:

    <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <input type="hidden" name="post_type" value="attorney" />
    <input type="text" value="" name="s" />
    <input type="submit" value="Search" />
    </form>