I use a feed from a manufacturer to upload to a WooCommerce custom field. The custom field expects a product id as input, but the feed is not aware of this as it's created by WooCommerce. I use SKU as the key to compare existing products with the feed.
The imported field is called {metaparent_sku[1]} and the content has several values separated by | , for example: BDCD7 | BDAUX | BDCA1 | ADUP89 These are unique product sku’s referring to products already in WooCommerce.
What I’d like to do is replace the sku value with the corresponding product ID value in as it exists already in WooCommerce.
I’ve been trying to use str_replace but can’t figure out how to set it up, if that's possible at all. Or should I use lookup? If anyone could help with some sample code I'd be very grateful.
To find the product ID by a sku field.
[wc_get_product_id_by_sku({sku[1]})]
So in your case that would be:
[wc_get_product_id_by_sku({metaparent_sku[1]})]
For when you have multiple sku's in one field make a custom function. Place the following function in the Function Editor.
/**
* Find product id(s) by sku(s)
* @param string $sku
* @return string with product id(s)
*/
function wp_all_import_get_product_ids_by_sku($sku, $seperator = "|") {
// define empty $product_ids
$product_ids = array();
// remove spaces from sku
$sku = str_replace(" ", "", $sku);
// convert to array
$skus = explode($seperator, $sku);
// find product ids
foreach ($skus as $sku) {
$product_ids[] = wc_get_product_id_by_sku($sku);
}
// return product ids
return implode(" | ", $product_ids);
}
Then use it like this
[wp_all_import_get_product_ids_by_sku({metaparent_sku[1]})]