php – Clear Woocommerce cart when sending multiple items by url-ThrowExceptions

Exception or error:

I need the Woocommerce cart to be cleaned in case I send more than four items to it via url.

I came up with this code, but it only cleans the cart if there are already five items in it.

//in functions.php

add_filter( 'woocommerce_add_to_cart_validation', 'remove_cart_item_before_add_to_cart', 20, 3 );
function remove_cart_item_before_add_to_cart( $passed, $product_id, $quantity ) {
    if( WC()->cart->get_cart_contents_count() >= 5  )
        WC()->cart->empty_cart();
    return $passed;
}

Another problem is that, even the code above that is not useful to me, does not work if I add multiple courses via url, as in:

https://exemple.net/cart?fill_cart=100,101,102,103,104,105,106

That is, the code in functions.php only works from the website, and not by url.

All I need is clear the cart when sending more than 4 items by url.

I prefer a solution in PHP, but a JS solution will do. Thanks for who can help me.

How to solve:

I found a solution using the free plugin Cart links for WooCommerce, and making a few change in its code.

I will describe below what I did:

1) To start install the plugin, this will allow you to add products using the fill_cart parameter in url (as described in my question)

2) edit the plugin file soft79-cart-links-for-woocommerce.php found at: yoursite/wp-content/plugins/soft79-cart-links-for-woocommerce/

3) go to line 141 or find the declaration of the method fill_cart

Inside the fill_cart method uncomment (or add) the code to clean the cart:

public function fill_cart( $fill_string ) {

    $original_notices = wc_get_notices();
    wc_clear_notices();

    ////Clear the cart
    //WC()->cart->empty_cart(); <-- uncomment here!

Save the file. Now any new items that arrive via url must clean the cart first.

Leave a Reply

Your email address will not be published. Required fields are marked *