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

2 Answers
2

The answer before mine shows you the problem about is_search() in your code.

To solve your problem, you can try to add some datas from your search form. In your WordPress you have a searchform.php, you can edit this file to add a new hidden field or use an ugly filter function like I have do here :

// Gives you the category where you want to search with from page ID
add_filter('wpse_306057_search_category_id', 'wpse_306057_search_category_id', 10, 1);
function wpse_306057_search_category_id($id = false) {
    switch($id)
    {
        case 100:
        $cat_id = 37;
        break;

        case 200:
        $cat_id = 24;
        break;


        case 201:
        case 202:
        case 203:
        $cat_id = array(57,99); // You may use multiple cats
        break;


        default:
        $cat_id = false;
        break;
    }
    return $cat_id;
}

// Add input hidden with "from page" for your search form
add_filter('get_search_form', 'wpse_306057_search_category_input', 10, 1);
function wpse_306057_search_category_input($form) {
    return str_replace('</form>', '<input type="hidden" name="search_from_page" value="'.get_queried_object_id().'" /></form>', $form);
}

// Add cat to your query
add_filter('pre_get_posts', 'wpse_306057_search_category', 10, 1);
function wpse_306057_search_category($query) {
    if(!is_admin()
    && $query->is_main_query()
    && $query->is_search()
    && !empty(@$_GET['search_from_page'])
    && apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']))
    {
        $query->set('cat', apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']));
    }
}

I haven’t tested the code, but it’s a good way to play with what you want to achieve.

Leave a Comment