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

时间:2018-05-04 10:24:23

标签: php wordpress woocommerce status orders

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码,该代码将使用"草稿"设置在订单商品中找到的产品。只有当订单获得"处理"或者"完成"状态(付费订单状态)

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' )
相关问题