如果订单完成,自动将 Woocommerce 产品设置为草稿状态 [英] Auto set Woocommerce product to draft status if order is completed
问题描述
在 WooCommerce 中,我想在订单完成时将产品设置为草稿状态......所以我想要的是让产品销售 1 次并在订单完成时传递到草稿状态.
In WooCommerce I would like to set products to draft status when Order is completed… So what I want is to make products to be sold 1 time and passed to draft when order get completed.
有什么想法吗?
推荐答案
试试下面的代码,将在订单项中找到的产品设置为草稿"仅当订单获得处理"时才处于状态或完成"状态(支付订单状态):
Try the following code, that will set the products found in order items with a "draft" status only when order get "processing" or "completed" statuses (paid order statuses):
add_action( 'woocommerce_order_status_changed', 'action_order_status_changed', 10, 4 );
function action_order_status_changed( $order_id, $old_status, $new_status, $order ){
// Only for processing and completed orders
if( ! ( $new_status == 'processing' || $new_status == 'completed' ) )
return; // Exit
// Checking if the action has already been done before
if( get_post_meta( $order_id, '_products_to_draft', true ) )
return; // Exit
$products_set_to_draft = false; // Initializing variable
// Loop through order items
foreach($order->get_items() as $item_id => $item ){
$product = $item->get_product(); // Get the WC_Product object instance
if ('draft' != $product->get_status() ){
$product->set_status('draft'); // Set status to draft
$product->save(); // Save the product
$products_set_to_draft = true;
}
}
// Mark the action done for this order (to avoid repetitions)
if($products_set_to_draft)
update_post_meta( $order_id, '_products_to_draft', '1' );
}
代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.
Code goes in function.php file of your active child theme (or active theme). Tested and works.
如果您希望仅定位已完成"订单,你可以替换这一行:
If you want to target only "completed" orders, you can replace this line:
if( ! ( $new_status == 'processing' || $new_status == 'completed' ) )
通过这个:
if( $new_status != 'completed' )
这篇关于如果订单完成,自动将 Woocommerce 产品设置为草稿状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!