WooCommerce: Search Products By SKU (Frontend)

The frontend WooCommerce product search, for some reason, doesn’t work for SKU values. If it does, then your theme developers were smart enough to include this in their code, because this is a big problem especially for B2B stores.

Today, we’ll study how to alter the product search query, as well as the wc_get_product_id_by_sku() function, which is super helpful to determine the product ID for a given SKU. Enjoy!

I know for sure there is a product with SKU = “24-WG085” on my dev site, yet there is no search result. The below snippet fixes this.

PHP Snippet: Enable Product Search by SKU (including variations)

/**
 * @snippet       Also Search by SKU @ Shop
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'posts_search', 'bbloomer_product_search_by_sku', 9999, 2 );
 
function bbloomer_product_search_by_sku( $search, $wp_query ) {
	global $wpdb;
	if ( is_admin() || ! is_search() || ! isset( $wp_query->query_vars['s'] ) || ( ! is_array( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] !== "product" ) || ( is_array( $wp_query->query_vars['post_type'] ) && ! in_array( "product", $wp_query->query_vars['post_type'] ) ) ) return $search;	
	$product_id = wc_get_product_id_by_sku( $wp_query->query_vars['s'] );
   if ( ! $product_id ) return $search;
   $product = wc_get_product( $product_id );
	if ( $product->is_type( 'variation' ) ) {
		$product_id = $product->get_parent_id();
	}
	$search = str_replace( 'AND (((', "AND (({$wpdb->posts}.ID IN (" . $product_id . ")) OR ((", $search );	
	return $search;   
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce Visual Hook Guide: Archive / Shop / Cat Pages
    I’ve created a visual HTML hook guide for the WooCommerce Archive Page (which is the same page for the Shop, Category, Tag pages). This visual guide belongs to my “Visual Hook Guide Series“, that I’ve put together so that you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can […]
  • WooCommerce: Hide Prices on the Shop & Category Pages
    Interesting WooCommerce customization here. A client of mine asked me to hide/remove prices from the shop page and category pages as she wanted to drive more customers to the single product pages (i.e. increasing the click-through rate). As usual, a simple PHP snippet does the trick. I never recommend to use CSS to “hide” prices, […]
  • WooCommerce: How to Remove the “Default Sorting” Dropdown
    If the WooCommerce product sorting functionality (“Default Sorting” dropdown) is a waste of space or you don’t need that select box at all, you may want to remove it. No matter if you prefer custom code or a simple plugin – hiding the product sorting dropdown is a piece of cake. Enjoy!

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

21 thoughts on “WooCommerce: Search Products By SKU (Frontend)

  1. Hi
    your code works perfect!!!

    I am wondering if this could also work for barcode field.
    I tried by replacing sku with metaname of my barcode field, but it doesn’t seem to work.
    Do you have any idea?

    1. Hello Nikos, this snippet features the wc_get_product_id_by_sku() function, which only works for SKUs. Using a custom field would require additional custom code. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. thanks man !

  3. I noticed the Search Products by SKU works on simple products, but it does not find the SKU of product variations. Is there a line we can add to pickup both?

    1. Works for me on any theme. Are you using the WordPress search bar or the WooCommerce one?

      1. Sorry. I might have had a little gremlin. I copied your code again into my snippet to replace what I had and it seems to work fine now. I should have done that before I wrote the comment.

  4. Hi, Redolfo!

    I tried to place this code to WPCode – create snippet but it’s not working and it actually goes into 500 error. Even if I add it to Flatsome Child: functions.php .. nothing. What am I doing wrong? Thank you!

    1. Not sure, works for me. What does the error say?

  5. Hi!

    Great addition, works well.
    However, it does not seem to find variations. I did see your Admin variant of this script does (was appended later), is it possible for this query as well, do you think?

    1. Try with the latest version please and let me know!

      1. I haven’t find varitations by this code too. Shows no reslut for the variation even was setted seperated sku id.

        1. Not sure, it works for me on my test site. Try switching temporarily to Storefront theme + disable all plugins except WooCommerce and try again

  6. HI Rudolfo, Previously I posted that this snippet works without any problem, but I found that the search does not find variables. It will find the parent, but if I search for the SKU of the variable, it will not find it. Thanks

    1. Fixed – take a look please!

  7. I used the “Search Products by SKU” snippet exactly as it was written and it worked instantly. Thanks. That’s a keeper.

  8. Hi Rodolfo,
    This code is just what I was looking for, unfortunately, doesn’t seem to be working on my b2b site. Do I need to change something from the code?
    Thanks for all your work!

    1. Hi Hamsa, this works on my development site. It should return the only product that has the specific SKU you enter in the search box, plus any other products that may have that string in the title or product description

      1. Thanks for your answer! And I don’t have to change anything on that code, right? I’m playing around with it, and search options on woocommerce adjustments with out luck.

        1. No problem. Are you experiencing problems with variations by any chance?

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *