Woocommerce: force to clear the cart after an order is placed in my site?

Viewed 784

I have a recurring issue in my Woocommerce site which is that the Cart is not cleared after an order is placed in my site.

I want to add a code in my_theme/functions.php to make sure the cart is cleared. I managed to create this code (below).

Will this be enough to get what I need?

add_action('woocommerce_new_order','clear_the_cart');

    function clear_the_cart() 
    {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }

Do I need to add a code to get the user ID and then clear the cart for that user?

If the cart is cleared for each user instead of for all users then, I guess I will need to get the current user id and then after execute the line of code to clear the cart for that user.

My question is whether I should clean the cart by user or globally?

I know how to grab the user id:

$user_ID = get_current_user_id();
....
1 Answers

Your method should work as expected when added to function.php.

You can also call it using WC()->cart->empty_cart();. the empty_cart() has a $clear_persistent_cart parameter, but true as default so your code is ok.

You can check in your theme and plugins if there's nothing strange hooked on the woocommerce_before_cart_emptied hook, which is triggered at the beginning of the empty_cart() method.

The empty_cart() will only empty the current user cart (the one passing the order), and if this code is not executed by another server (eg: queue) or PHP process: the customer's session data will be available, and so the cart can be emptied. This won't clear every customer cart content (to resume, empty_cart() must be called from a customer request (ajax or not), and will clear this customer cart.)

On contrary, a webhook or an admin-ajax request from your payment provider to your Woocommerce gateway, or a CRON, will not clear any cart (you don't have session data). If that's your case you'll need something like: saving the customers ID somewhere in DB, then hook somewhere (like init) with a method that check "If user id in DB array, clear_cart(), then remove from DB array".

Now, Woocommerce should by default clear the cart after the order is complete. Here are few things to try and tests:

  • change your add_action by add_action( 'woocommerce_new_order', 'clear_the_cart', 50, 3 );, increasing the $priority to be ran at last
  • you can test using the woocommerce_order_status_completed hook if it matches your requirement
  • does this happen to every customer? And you directly on local, dev, or production? If so, can you try adding a wp_die() or related, in your clear_the_cart() method to validate that this code is triggered after your order
  • do you use a custom woocommerce payment gateway? Please add details like WP version, Woocommerce version, payment gateway, etc.

Note that some plugins (and so some custom code on hooks) can prevent the cart from emptying after order completion (see)

Related