Set Woocommerce products status to draft when Order is completed

woocommerce

Hello, welcome to therichpost.com. In this post, I will tell you, Set Woocommerce products status to draft when Order is completed.  WordPress is the best cms and Woocommerce is the best Ecommerce plugin. WordPress hooks(add_action, add_filter) give us the power to edit or change the code without interruption into the files and this is the best thing about wordpress. 

Here is the code for Set Woocommerce products status to draft when Order is completed because I want to sell my product only once and here is the working code and you need to paste this into your theme’s functions.php file:
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 != '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' );
}

 There are so many codes in woocommerce and i will let you know all. Please do comment if you any query     related  to   this post. Thank you. Therichpost.com

Comments

3 responses to “Set Woocommerce products status to draft when Order is completed”

  1. Junaid Avatar
    Junaid

    Hello!
    I want to change the status of out of stock product from publish to draft automatically in wordpress. Can you please help me out of that.

    Thanks

    1. Ajay Malhotra Avatar

      I will share the code snippet soon.
      Thanks

      1. Junaid Avatar
        Junaid

        Thanks for your reply and kindly also tell me in which file to put this code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.