Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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' );
share|improve this question

1 Answer 1

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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