Searching through different categories on different pages code is not working

I am adding a default WordPress Search widget through Elementor on two of my page, page X and page Y. Page X ID = 100, page Y ID = 200. I want the user to be able to search through category 37 when he is on page X, and be able to search through category 24 when he is on page Y. I wrote this code:

function searchcategory($query) {
if (! is_admin() && $query->is_main_query() && $query->is_search()) {
if (is_page(100)) {
$query->set(‘cat’,37);}
else if (is_page(200)) {
$query->set(‘cat’,24);}
}
}

add_filter(‘pre_get_posts’,’searchcategory’);

However, it does not work properly. It returns pages which have different categories and IDs etc. Also, results are same on both page X and page Y. Can anyone help editing the code?

Note: the code below works fine though:

function searchtest($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( ‘cat’, 39 );
}
}
add_action( ‘pre_get_posts’, ‘searchtest’ );

Read more here:: Searching through different categories on different pages code is not working

Leave a Reply

Your email address will not be published. Required fields are marked *