从sku获取产品对象并在WooCommerce中更新价格 [英] Get the product object from sku and update the price in WooCommerce

查看:133
本文介绍了从sku获取产品对象并在WooCommerce中更新价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的功能文件中通过product_id更新产品?

我尝试使用以下代码,但未成功:

$_pf = new WC_Product_Factory();  
$product_id = wc_get_product_id_by_sku( $sku );
$_product = $_pf->get_product($product_id);
$_product->set_price('225');

解决方案

从WooCommerce 3开始,不推荐使用带有get_product()方法的new WC_Product_Factory()并简单地由函数wc_get_product()代替.

要更新价格,您必须更新价格和常规价格(或价格和销售价格) ...

save()方法对于捕获最后的数据也是必需的.

因此,要从现有产品SKU中获取WC_Product对象 ,并在其上使用任何可用方法,请执行以下操作:

$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);
}

经过测试,可以正常工作.

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() 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.

这篇关于从sku获取产品对象并在WooCommerce中更新价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆