How to include SKU in WooCommerce search?

Hello, I am trying to include SKU in the WooCommerce search, but I don’t know how. I have added SKU codes to my products in the inventory section, but when I search for them on my website, they don’t appear. I want to enable SKU search for my customers, so they can find the product they want by its unique identifier. I often share my products on social media with the SKU, so it’s important that the search can find it. Can anyone help me with this problem? I appreciate any help you can provide.

By default, WooCommerce does not include the SKU in the search query. If you want to allow your customers to search for products by their SKU, you need to add some custom code to your site.

function search_by_sku( $search, $query_vars ) {
	global $wpdb;
	if( !empty($query_vars->query['s']) ){
	    $args = array(
	        'posts_per_page'  => -1,
	        'post_type'       => 'product',
	        'meta_query' 	  => array(
	                'key' 		=> '_sku',
	                'value' 	=> $query_vars->query['s'],
	                'compare' 	=> 'LIKE'
	    $posts = get_posts($args);
	    if(empty($posts)) {
	    	return $search;
	    $post_ids = array();
	    foreach($posts as $post){
	        $post_ids[] = $post->ID;
	    if(sizeof( $post_ids ) > 0 ) {
	            $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $post_ids ) . ")) OR (", $search);
	return $search;
add_filter( 'posts_search', 'search_by_sku', 999, 2 );

Add this code snippet to your theme’s functions.php file. It will make WooCommerce search for products with an SKU that matches the search term. Note that this will also exclude any products that do not have an SKU from the search results.