-3

I want to make status from "pending" to "completed" after using 100% discount coupon

I've been making a script for my Wordpress site, bc when I use 100% coupon it makes order status "processing" so it won't enroll my courses to user.

I have found this script info functions.php, but it makes all orders, completed. I want to make all orders, which total cart sum is = "0". Can you help me upgrade this code?

/**
 * Auto Complete all WooCommerce orders.
 */

if ( WC()->cart->total == 0 ) {

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}
}
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
Bongoja
  • 27
  • 6
  • 2
    Please explain the issue better, do you want to complete order automatically when they used a specific coupon, or when the total is 0? – Ali_k Apr 22 '21 at 13:37
  • I want to make status from "pending" to "completed" after using 100% discount coupon. I will update post in a sec – Bongoja Apr 22 '21 at 14:00

1 Answers1

0

The cart is no longer relevant after the order is created, so you need to check the order total inside the function and act based on that. Your code should looks something like this:

add_action('woocommerce_checkout_order_processed', 'custom_woocommerce_auto_complete_order');
function custom_woocommerce_auto_complete_order($order_id)
{
    if (!$order_id) {
        return;
    }

    $order = wc_get_order($order_id);
    if ($order->get_total() == 0) {
        $order->update_status('completed');
    }
}
Ali_k
  • 1,642
  • 1
  • 11
  • 20
  • that's would probably work but now i realized when there is no payment is shows me no thankyou page, it refreshes on www.com/order (the same page i place order). Do you know the way to solve this? – Bongoja Apr 22 '21 at 15:10
  • I mean the optimal way would be running this code when order has been placed, no when it shows thank you page – Bongoja Apr 22 '21 at 15:14
  • OK I GOT THIS - thank you add_action('woocommerce_checkout_order_processed', 'custom_woocommerce_auto_complete_order'); function custom_woocommerce_auto_complete_order($order_id) { if (!$order_id) { return; } $order = wc_get_order($order_id); if ($order->get_total() == 0) { $order->update_status('completed'); } } – Bongoja Apr 22 '21 at 15:19
  • 1
    Great, if this answer was helpful, don't forget to mark it. – Ali_k Apr 22 '21 at 15:21
  • 1
    You need to do with another hook `woocommerce_thankyou`, same code, only replace `$order->update_status('completed');` with `wp_safe_redirect( 'https://example.com' ); exit;` – Ali_k Apr 22 '21 at 15:34