This is a continuation of my previous post: Gist: Skip the cart page in WooCommerce after adding a product. To better understand this, please read the previous post and then proceed here.
In my previous post, we’ve managed to streamline the checkout user experience by skipping the cart entirely. But after thorough testing, you’ll realize that there’s a big UX issue that needs to be resolved. Below is an explanation of a scenario of this.
Customer experience scenario:
- customer adds a product to the cart session
- customer is redirected to the checkout page (cart skipped wooh!!)
- customers decides to go back to shop page and selects a different product
- customer is redirected again to checkout page
- customer sees there are two products in the order review
- customer realizes there is no way to remove the previous product and gets frustrated trying
- customer leaves
How to fix this?
There are a lot of ways to do go with this if you are creative enough, but this post will only focus on one solution, which is to force WooCommerce to only have one product in the cart session.
What we need to do in order to achieve this is to clear the cart session every time a product is added to the cart. The gist below will make this work:
For this example, we are creating a PHP function to hook to the
woocommerce_add_to_cart_product_id filter. This filter is applied when a product is added to the cart session, so we can modify the results. The line
WC()->cart->empty_cart() is the method that clears the cart.
WC() is the main instance of WooCommerce which was added since version 2.1 so we won’t need to use the
$woocommerce global variable anymore. This instance holds instances of the cart, customer, session, etc. in its properties/variables, hence we can use the
empty_cart() method of the cart instance.
There are still other methods to streamline the checkout experience in WooCommerce, which I will be blogging about it in the future. Let me know your thoughts in the comments below. Cheers!