[英]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/ 我有woocommerce商店,例如:example.com/store/
And I am creating the some product sales page in outside of wordpress : example.com/upsell.php 我正在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). 现在,一旦您访问example.com/upsell.php,我想清除购物车,因为我们在加售中有多个步骤,最后我们发送了一个网址请求,将商品添加到购物车中(example.com/store/购物车/加到购物车= 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. 在主题的functions.php
或自定义插件文件中使用以下代码片段。
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. 将上述代码添加到主题的functions.php
文件中。
Then redirect to a page by adding clear-cart
query string in your URL & that will clear all cart items. 然后通过在URL中添加clear-cart
查询字符串重定向到页面,这将清除所有购物车项目。
We can use this function in any URL. 我们可以在任何URL中使用此功能。
http://example.com?clear-cart http://example.com?clear-cart
or 要么
http://example.com/sample-page/?clear-cart 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. 我将使用$ _SERVER ['REQUEST_URI']来获取页面的当前URL,以便您可以测试是否在加售页面上。
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 您需要在wp实例中创建Web api,使用此代码清除购物车
global $woocommerce;
$woocommerce->cart->empty_cart();
and call that api on upsell.php file. 并在upsell.php文件中调用该api。 You can even use HTTP_REFERER to check whether user directly hit the upsell.php url or not. 您甚至可以使用HTTP_REFERER来检查用户是否直接点击了upsell.php网址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.