Get the product object from sku and update the pri

2019-08-13 10:13发布

问题:

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.