【发布时间】:2021-12-03 03:18:23
【问题描述】:
当我商店中的任何产品库存达到 0 时(所有变体),我需要它执行以下操作:
- 将相关产品保存为草稿。
- 将此产品复制到新产品中。
- 将新产品中的每个变体设置为库存水平为 1。
- 将新产品的名称更改为与旧产品的名称相同(不附加“ (Copy)”)。
- 发布新产品。
我在functions.php 中有我的代码,它正在复制产品。我遇到问题的地方是获取新产品的 ID,设置其名称,然后将其变体设置为每个都有 1 个库存。任何帮助将不胜感激!
function order_checker($order_id) {
// get the order
$order = new WC_Order($order_id);
// get the products from the order
$all_products = $order->get_items();
// loop through each product in the order
foreach ($all_products as $product) {
// get the product object
$product_object = wc_get_product($product['product_id']);
// if the product is a variable product
if ($product_object->is_type('variable')) {
// set "soldout" variable to true by default
$soldout = true;
// loop through the product variations and set "soldout" variable to false if they aren't all at 0 stock
foreach ($product_object->get_available_variations() as $variation) {
if ($variation['is_in_stock']) $soldout = false;
}
// if the product is sold out
if ($soldout) :
// save it as a draft
wp_update_post(array(
'ID' => $product['product_id'],
'post_status' => 'draft'
));
// duplicate it to a new product
$duplicate_product = new WC_Admin_Duplicate_Product;
$new_product = $duplicate_product -> product_duplicate($product_object);
// grab the new product ID
$new_product_id = $new_product->get_id();
// grab the new product title
$new_product_title = get_the_title($new_product_id);
// remove " (Copy)" from the new product title
$new_product_title = str_replace(' (Copy)', '', $new_product_title);
// get an array of variation ids for the new product
$new_variation_ids = $new_product->get_children();
// loop through the variation ids
foreach ($new_variation_ids as $new_variation_id) {
// get the variation object
$variation_object = new WC_Product_variation($new_variation_id);
// set the stock quantity to 1
$variation_object->set_stock_quantity(1);
// set the stock status to in stock
$variation_object->set_stock_status('instock');
// save and refresh cached data
$variation_object->save();
}
// set new product title and publish it
wp_update_post(array(
'ID' => $new_product_id,
'post_title' => $new_product_title,
'post_status' => 'publish'
));
?><script>console.log("This product has sold out!");</script><?php
else :
?><script>console.log("This product still has some options in stock!")</script><?php
endif;
}
}
}
add_action('woocommerce_thankyou', 'order_checker', 10, 1);
【问题讨论】:
-
当您可以简单地将步骤 3 应用于现有产品时,为什么还要执行所有这些步骤?其他步骤的优势是什么?
-
它需要是我的客户的报告和其他要求的新产品。
标签: php wordpress woocommerce product variations