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' );
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.'" />';
}
| improve this answer | |
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>
| improve this answer | |
  • This is exactly the same thing that i suggested in my answer. Expect i gave a dynamic solution and you came up with static solution with post type "attorney". – JItendra Rana Apr 22 '17 at 5:02
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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