Follow me on social media:

How To Retrieve Product By SKU in WooCommerce (Code Snippet)

WooCommerceBeen a while since I’ve posted here, so I thought I’d drop a little code snippet helper function that you can put in your functions.php or plugin for retrieving a product via the SKU in WooCommerce.

Since Woo doesn’t provide a helper function for retrieving a product via SKU this has come in handy a number of times. Hope it helps you in whatever project you’re facing.

function get_product_by_sku($sku) {
	global $wpdb;
 
	$product_id = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku
		)
	);
 
	if ($product_id)
		return get_product($product_id);
 
	return null;
}

Leave a Reply

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