Quantcast
Viewing latest article 8
Browse Latest Browse All 8

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

Image may be NSFW.
Clik here to view.
WooCommerce
Been 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;
}

Viewing latest article 8
Browse Latest Browse All 8

Trending Articles