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 a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us