Get the product object from sku and update the price in WooCommerce

烈酒焚心 提交于 2019-12-11 04:55:53

问题


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');

回答1:


Since WooCommerce 3, new WC_Product_Factory() with get_product() method is deprecated and replaced simply by the function wc_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:

$new_price   = '225'; // New price
$_product_id = wc_get_product_id_by_sku( $sku );

if ( $_product_id > 0 ) {
    // Get an instance of the WC_Product Object
    $_product = wc_get_product( $_product_id );

    $_product->set_regular_price($new_price); // Set the regular price
    $_product->set_price($new_price); // Set the price
    $_product->save(); // Save to database and sync
} else {
    // Display an error (invalid Sku
    printf('Invalid sku "%s"… Can not update price.', $sku);
}

Tested and works.



来源:https://stackoverflow.com/questions/56353114/get-the-product-object-from-sku-and-update-the-price-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!