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' );
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 !
You can also do it using a WordPress filter pre_get_posts. Add or remove the post types as you see fit.
I was able to do this by creating a custom search form by adding this:
So, my search form looks like this: