且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Woocommerce 3 中以编程方式更新产品库存

更新时间:2023-11-30 12:50:22

更新 2

由于 woocommerce 3缺货"产品状态保存在 2 个位置:

Since woocommerce 3 "outofstock" product status is saved in 2 locations:

  1. 作为 _stock_status 元键的发布元数据(和以前一样).
  2. 作为帖子术语名称 outofstock 剩下的 product_visibility 自定义分类法
  1. As post meta data for _stock_status meta key (just as before).
  2. As a post term name outofstock remaining to product_visibility custom taxonomy

这意味着您只错过了一步(第 3 步):

That means that you missed just a step (the step 3):

$out_of_stock_staus = 'outofstock';

// 1. Updating the stock quantity
update_post_meta($product_id, '_stock', 0);

// 2. Updating the stock quantity
update_post_meta( $product_id, '_stock_status', wc_clean( $out_of_stock_staus ) );

// 3. Updating post term relationship
wp_set_post_terms( $product_id, 'outofstock', 'product_visibility', true );

// And finally (optionally if needed)
wc_delete_product_transients( $product_id ); // Clear/refresh the variation cache

希望它适用于您的 cron 作业.

It hope that it will work with your cron job.

原答案

自 woocommerce 3 以来,您的代码有点过时,并且没有专门针对产品变体的库存状态设置...

Your code is a bit outdated since woocommerce 3 and there is no specifically a stock status setting for product variations...

woocommerce 中有一个专用函数可以从您可以使用的 sku:

There is a dedicated function in woocommerce to get the product Id from the sku that you could use:

wc_get_product_id_by_sku( $product_sku );

对于父变量产品,您应该不需要启用库存管理,因为这已在其每个产品变体中完成(因此在产品变体级别).

For the parent variable product, you should not need to enabled stock management as this is done in each of its product variations (so at the product variation level).

从 woocommerce 3 开始,outofstock"库存状态也被管理认为自定义分类 product_visibility 术语名称是 outofstock.所以更新帖子元是不够的.

Since woocommerce 3, the "outofstock" stock status is also managed thought a custom taxonomy product_visibility which term name is outofstock. So updating post meta is not enough.

也***使用 新的 CRUD setter 和 getter 方法 与 woocommerce 3 一起引入.

Also is better to use the new CRUD setters and getters methods introduced with woocommerce 3.

所以试试下面的代码:

// get the product ID from the SKU
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

// Get an instance of the WC_Product object
$product = new WC_Product( $product_id );

// Get product stock quantity and stock status
$stock_quantity = $product->get_stock_quantity();
$stock_status   = $product->get_stock_status();

// Display stock quantity and status
echo '<p>Product Stock quantity: ' . $stock_quantity . '</br>
    Product Stock status: ' . $stock_status . '</p></br>';

// Set product stock quantity (zero) and stock status (out of stock)
$product->set_stock_quantity();
$product->set_stock_status('outofstock');

// Save the data and refresh caches
$product->save();

经过测试并在正常环境下工作(但显然不是使用 cron 作业)

Tested and works in a normal context (but apparently not with a cron job)