0
votes

I've encountered a weird thing in WP WooCommerce and I can't understand nor fix it myself.

Thing is I've added a clear button in my checkout page, that button redirects me to my homepage and adds a ?clear param. Then I check if that param is set and if it is set then the cart is cleared;

Code:

if(isset($_POST["clear_cart"]))
{
    header("Location: https://examplepage.com?clear");
}

add_action( 'init', 'woocommerce_clear_cart_url' );

function woocommerce_clear_cart_url() 
{
    global $woocommerce;

    if(isset( $_GET['clear'])) 
    {
         $woocommerce->cart->empty_cart(); 
    }
}

Now the bug/error thing.

This code works... Once. I'll do my best to explain now. When I click the clear button for the first time - it works. I'm being redirected to my homepage, cart is cleared, everything works.

When I go and add some products again and then I clear the cart I get redirected to my homepage again (first 4 lines of code) but my cart isn't cleared now. To get it cleared I have to change my param to something like

?clear=true

Then I do the same thing and after clicking clear cart button it redirects me again and the cart isn't cleared. If I again change the param to

?clear=true

it doesn't work this time - because it worked before. Changing the param to

?clear=true1

clears the cart.

I hope you've already understand what I'm talking about. I've tried various params instead of "clear" and everytime the same thing happens.

When I also tried echoing something within

function woocommerce_clear_cart_url() 

it also worked only once. I'm out of ideas.

Thank you.

2
why you redirect user first and then clear cart, just add ajax call on clear cart button and clear cart in ajax when response come, redirect user to home page .Mahipal Patel
You are right, that has been changed already. But it still doesn't work as intended.SomeRandomName
Same stuff happens - I get redirected to my homepage, cart is somewhat cleared (it shows that I still have some products in my cart but when I go to check them it says it's empty).SomeRandomName

2 Answers

0
votes

Try below code

add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
  global $woocommerce;
  if(isset($_POST["clear_cart"]))
  {
    $data= $woocommerce->cart->empty_cart(); 
    if(is_null($data) == 1 ){
     wp_redirect( site_url() ); 
     exit; 
  }
}

Assuming your html code is something like below :

<form method="post">
 <input type="submit" name="clear_cart" value="1"> 
</form>
0
votes

You need to try this code for your error.

add_action("template_redirect", 'e_coding_hub_redirection_function');

function e_coding_hub_redirection_function(){

global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count == 0){
        //wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
        wp_redirect( site_url() );
    }
}