1

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:

<?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' );

3 Answers 3

3

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');
2
  • Add this to functions.php file of your theme. Also works with custom post types.
    – Dushan
    Commented Dec 28, 2020 at 5:48
  • 1
    I think this is the best solution. It doesn't allow users tо bypass it like in the other answers. Commented Jul 29, 2021 at 20:19
0

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>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.