繁体   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