Home Woocommerce Hooks Set Woocommerce products status to draft when Order is completed

Set Woocommerce products status to draft when Order is completed

by therichpost
3 comments
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

You may also like

3 comments

Junaid September 13, 2020 - 8:13 am

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

Reply
Ajay Malhotra September 13, 2020 - 8:15 am

I will share the code snippet soon.
Thanks

Reply
Junaid September 13, 2020 - 8:40 am

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

Reply

Leave a Comment

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