用户离开Woocommerce中的某个页面后,便会清空购物车 [英] Empty cart once a user leaves a certain page in Woocommerce
本文介绍了用户离开Woocommerce中的某个页面后,便会清空购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我们正在构建一个具有自定义页面的网站,该页面调用WooCommerce购物车中的商品。但是,一旦用户离开该页面,我们想做的就是清空购物车。这可能吗?
So we're building a site that has a custom page that's calling the items in a WooCommerce cart. But what we wanted to do is empty that cart once a user leaves that page. Is this possible?
我们发现了这段代码可能会对我们有所帮助,但是当我们进入管理页面时,我们一直遇到致命错误,而这似乎只有在进入管理页面时才会发生部分:
We found this code that will maybe help us but we kept getting a fatal error when we go to the admin page and this only seems to happen when we go to the admin section:
致命错误:在null上调用成员函数
empty_cart()
在第746行的/home/client/public_html/wp-content/themes/wp-theme/functions.php
中
这是我们的代码:
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if ($_SERVER['REQUEST_URI'] !== 'https://www.oursite.com/fake-cart-page/') {
$woocommerce->cart->empty_cart();
}
}
谢谢!
推荐答案
我们知道了!所以这就是我们要做的:
We figured it out! So this is what we did:
//we inserted a script in wordpress and put it in the head
add_action( 'wp_head', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
//we used the jquery beforeunload function to detect if the user leaves that page
?>
<script>
jQuery(document).ready(function($) {
$(window).bind('beforeunload', function() {
//Used WordPress to help jQuery determine the page we're targeting
//pageID is the page number of the page we're targeting
<?php if(!is_page(pageID)):
//empty the cart
$woocommerce->cart->empty_cart(); ?>
<?php endif; ?>
});
});
</script>
<?php } ?>
这篇关于用户离开Woocommerce中的某个页面后,便会清空购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文