简体   繁体   中英

How to clear the woocommerce cart when visiting the particular page (outside of wordpress) custom php page

I am having the woocommerce store like : example.com/store/

And I am creating the some product sales page in outside of wordpress : example.com/upsell.php

Now I want to clear the cart once you visit the example.com/upsell.php, because we are having multiple step in the upsell and finally we are send a url request to add the products in the cart (example.com/store/cart/?add-to-cart=1,5,8).

Whenever you visit the upsell page we need to clear the cart session.

How can clear the cart session from the upsell page?

You need to add an action that will clear cart items in template redirect hook.

In the custom function, check the current page slug & then clear the cart as per our condition.

Use the below code snippet in your theme's functions.php or custom plugin file.

add_action( 'template_redirect', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    global $post;
    $slug = $post->post_name;
    if($slug == 'sample-page') {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}

Update

If you don't like hard coding the page slug, there is also a better method.

add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    if ( isset( $_GET['clear-cart'] ) ) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}

Add the above code in your theme's functions.php file.

Then redirect to a page by adding clear-cart query string in your URL & that will clear all cart items.

We can use this function in any URL.

http://example.com?clear-cart

or

http://example.com/sample-page/?clear-cart

I'd use $_SERVER['REQUEST_URI'] to get the current URL of the page so you can test whether you're on the upsell page.

You'll need to use the following function to clear the cart

global $woocommerce;
$woocommerce->cart->empty_cart();

you need to create web api in wp instance which clears cart using this code

global $woocommerce;
$woocommerce->cart->empty_cart();

and call that api on upsell.php file. You can even use HTTP_REFERER to check whether user directly hit the upsell.php url or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM