Categories

Friday, April 19, 2024
#919814419350 therichposts@gmail.com
Woocommerce Hooks

Set Woocommerce products status to draft when Order is completed

How to add download pdf link in woocommerce single product page?

Set Woocommerce products status to draft when Order is completed

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

3 Comments

Leave a Reply

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