Following Update WooCommerce product stock from csv
How do I modify the code if the SKU is not a product SKU but a product variant SKU? So how do I update the stock of a product variant if I only know the SKU of the variant? There is no wc_get_variant_id_by_sku...
CodePudding user response:
The datastore function checks for both Product and Product variation in the function as shown below.
/**
* Return product ID based on SKU.
*
* @since 3.0.0
* @param string $sku Product SKU.
* @return int
*/
public function get_product_id_by_sku( $sku ) {
global $wpdb;
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
$id = $wpdb->get_var(
$wpdb->prepare(
"
SELECT posts.ID
FROM {$wpdb->posts} as posts
INNER JOIN {$wpdb->wc_product_meta_lookup} AS lookup ON posts.ID = lookup.product_id
WHERE
posts.post_type IN ( 'product', 'product_variation' )
AND posts.post_status != 'trash'
AND lookup.sku = %s
LIMIT 1
",
$sku
)
);
return (int) apply_filters( 'woocommerce_get_product_id_by_sku', $id, $sku );
}
So the function can be used for variations as well.
wc_get_product_id_by_sku($sku);
- It will return the variation ID if a variation SKU is passed to the function.