簡體   English   中英

如果訂單完成,則自動將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( ! ( $new_status == 'processing' || $new_status == 'completed' ) ) 

通過這個:

  if( $new_status != 'completed' ) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM