Best Premium and Free WordPress Themes › Forums › Online Shop › Search by category doesn't work › Reply To: Search by category doesn't work
I added this to the functions.php under Appearance>Editor and it solved all my trouble. It allows the search to use the categories, and it excludes any out of stock items, as well as displays the search results correctly.
/**
* Adds Category taxonomy query to WP search query
* This addition will make the search more relevant
* @param type $query
*/
function search_filter($query) {
if($query->is_search()) {
// category terms search.
if (isset($_GET[‘product_category’]) && !empty($_GET[‘product_category’])) {
$tax_query = array(
‘taxonomy’ => ‘product_cat’,
‘terms’ => array($_GET[‘product_category’]),
‘field’ => ‘id’,
‘operator’ => ‘IN’,
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars[‘tax_query’] = $query->tax_query->queries;
}
}
}add_action(‘pre_get_posts’,’search_filter’);
add_action( ‘pre_get_posts’, ‘iconic_hide_out_of_stock_products’ );
function iconic_hide_out_of_stock_products( $q ) {
if ( ! $q->is_main_query() || is_admin() ) {
return;
}if ( $outofstock_term = get_term_by( ‘name’, ‘outofstock’, ‘product_visibility’ ) ) {
$tax_query = (array) $q->get(‘tax_query’);
$tax_query[] = array(
‘taxonomy’ => ‘product_visibility’,
‘field’ => ‘term_taxonomy_id’,
‘terms’ => array( $outofstock_term->term_taxonomy_id ),
‘operator’ => ‘NOT IN’
);$q->set( ‘tax_query’, $tax_query );
}
remove_action( ‘pre_get_posts’, ‘iconic_hide_out_of_stock_products’ );
}