如果订单完成,则自动将Woocommerce产品设置为草稿状态



在WooCommerce中,我想在订单完成时将产品设置为草稿状态...所以我想要的是使产品销售 1 次,并在订单完成后传递给草稿。

知道吗?

请尝试以下代码,仅当订单获得"正在处理"或"已完成"状态(已付款订单状态(时,才会将订单项中找到的产品设置为"草稿"状态:

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

代码进入函数.php活动子主题(或活动主题(的文件。经过测试并工作。

如果您只想定位"已完成"的订单,则可以替换以下行:

if( ! ( $new_status == 'processing' || $new_status == 'completed' ) )

通过这个:

if( $new_status != 'completed' )

最新更新