The better option may be to use the pre_get_posts
hook instead to modify the query before it gets requested instead of creating your own query. Here’s what it would look like:
/**
* Modify Theme Queries
* - https://developer.wordpress.org/reference/hooks/pre_get_posts/
* - https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
*
* @param $query
*
* @return void
*/
function theme_pgp( $query ) {
if( is_admin() ) {
return; // If we're in the admin panel - drop out
}
if( $query->is_main_query() && $query->is_search() ) { // Apply to all search queries
// IF our category is set and not empty - include it in the query
if( isset( $_GET['category'] ) && ! empty( $_GET['category'] ) ) {
$query->set( 'tax_query', array( array(
'taxonomy' => 'product-category',
'field' => 'slug',
'terms' => array( sanitize_text_field( $_GET['category'] ) ),
) ) );
}
}
}
add_action( 'pre_get_posts', 'theme_pgp' );
At this point on your search page you can just use your standard loop instead of the custom WP_Query:
if( have_posts() ) {
while( have_posts() ) {
the_post();
the_title();
}
}