Reputation: 21
I am using a custom woocommerce product search in my wordpress site where it searchs only in product titles. I would like to include the search in category names too. So if someone search a text, and if that's exists in product category name, all those products under that category also need to be listed.
Here is code I am using:
function wc_filter_search_by_title_only( $search, &$wp_query ) {
global $wpdb;
$not_allowed_post_types = apply_filters( 'wc_filter_search_not_allowed_array', array(
'product', //Default WooCommerce products post type
'shop_webhook', //MyStyle Custom post type
) );
if ( empty( $search ) || ! in_array( $wp_query->query_vars['post_type'], $not_allowed_post_types ) ) {
return $search; // skip processing - no search term in query
}
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search =
$searchand = '';
foreach ( (array) $q['search_terms'] as $term ) {
$term = esc_sql( $wpdb->esc_like( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
return $search;
}
add_filter( 'posts_search', 'wc_filter_search_by_title_only', 500, 2 );
Kindly let me know if anyway I can implement this.
Thank you in advance.
Upvotes: 2
Views: 626
Reputation: 1766
The easiest way really is to use SearchWP with its WooCommerce extension. Besides, it gives you a lot more functionality than just that.
Upvotes: 0