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

Auto set Woocommerce product to draft status if order is completed

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

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

If you want to target only "completed" orders, you can replace this line:

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

by this one:

  if( $new_status != 'completed' )