Home / Admin / Advanced Search Query
Duplicate Snippet

Embed Snippet on Your Site

Advanced Search Query

*Advanced Concept* Extends default search to target category search. Require advanced search form and additional setup as suggested.

Code Preview
php
<?php
function filter_search_by_multiple_categories( $query ) {
    // Only modify the main query on the front-end search results page
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        
        // Check if category_name is set and is an array
        if ( isset( $_GET['category_name'] ) && is_array( $_GET['category_name'] ) ) {
            
            // Get the array of category slugs
            $categories = $_GET['category_name'];
            
            // Implode the array into a comma-separated string
            // WordPress accepts comma-separated category slugs in the category_name parameter
            $category_string = implode( ',', $categories );
            
            // Set the category_name query variable
            $query->set( 'category_name', $category_string );
        }
    }
    return $query;
}
add_action( 'pre_get_posts', 'filter_search_by_multiple_categories' );   

Comments

Add a Comment