How can I update a product by product_id in my functions file?
I tried using the below code but to no success:
$_pf = new WC_Product_Factory();
$product_id = wc_get_product_id_by_sku( $sku );
$_product = $_pf->get_product($product_id);
$_product->set_price('225');
Since WooCommerce 3,
new WC_Product_Factory()
withget_product()
method is deprecated and replaced simply by the functionwc_get_product()
.To update price, you have to update the price and the regular price (or the price and the sale price)...
Also the
save()
method is necessary to grab the data at the end.So to get the
WC_Product
Object from an existing product SKU and to use on it any available method, do the following:Tested and works.