WordPress   

Search Woocommerce products by SKU in WordPress website

//Include Woocommerce Product SKU in Search
function rp_search_products_sku($query) {
    global $wpdb;
	$search_query = get_search_query();
	if(empty($search_query)){
		return $query;
	}
	else{
		$args = array(
			'posts_per_page' => -1,
			'post_type' => 'product',
			'fields' => 'ids',
			'meta_query' => array(
				array(
					'key' => '_sku',
					'value' => $search_query,
					'compare' => 'LIKE'
				)
			)
		);
		$posts = get_posts($args);
		if(empty($posts)) {
			return $query;
		}
		else{
			$query = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $posts ) . ")) OR (", $query);
			return $query;
		}
	}
}
add_filter( 'posts_search', 'rp_search_products_sku', 999, 2 );
Need Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us