Can anyone tell how to use new built-in filter/search functionality to search products by SKU.
Second that. Would be good to have in the Products Filter Search. My global search in WP already returns them fine (I’m using a code snippet to make that happen) but it’s not working on this Bricks Element.
I third that.
@Allucinante Would you be willing to share your code snippet? I have a site-wide search, but it only pulls from product title, not SKU, description, or Tag (which all would be useful.)
TIA
To search by SKU, you need to modify the default WooCommerce search. You can achieve this by installing the Relevanssi Light plugin.
Here you go. I’m using a modified version, based on this on. Remember, this only works with the WP Search widget, not in the product search of the Bricks products filter element:
guys _sku is just a custom field
if you want to make custom field filtering with _sku s here this is the setup;
and if you want to add the _sku field to the normal site global search here use this snippet.
enjoy…
// Function to modify the search query to include SKU in WooCommerce product searches
function search_by_sku_in_woocommerce( $search, $wp_query ) {
global $wpdb;
// Check if it's a search query and WooCommerce is active
if ( ! $wp_query->is_search() || ! $wp_query->is_main_query() || ! is_search() || ! class_exists( 'WooCommerce' ) ) {
return $search;
}
// Get the search query
$search_term = $wp_query->query_vars['s'];
// Only modify the search if there is a search term
if ( ! empty( $search_term ) ) {
// Get the current search query parts
$search = " AND ({$wpdb->posts}.post_title LIKE '%" . esc_sql( $search_term ) . "%'
OR {$wpdb->posts}.post_content LIKE '%" . esc_sql( $search_term ) . "%'
OR EXISTS (
SELECT 1 FROM {$wpdb->postmeta}
WHERE {$wpdb->postmeta}.meta_key = '_sku'
AND {$wpdb->postmeta}.meta_value LIKE '%" . esc_sql( $search_term ) . "%'
AND {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID
))";
}
return $search;
}
// Hook the function into the 'posts_search' filter
add_filter( 'posts_search', 'search_by_sku_in_woocommerce', 10, 2 );
Thanks for the snippet!
I’ve added this to my website via code snippet plugin and activated, but it’s still not searching by SKU…
interesting I tested on my woocommerce site and it works fine
I cant say why didn’t work for you.
¯_(ツ)_/¯
don’t use any other search plugin top of it
One possible solution is to manually rebuild the WordPress search index. However, the exact steps may vary depending on your specific setup and any plugins you are using for search functionality. If you are using a search plugin like FiboSearch, SearchWP, Relevanssi, etc., check the plugin settings or documentation for an option to rebuild the index.