如何在x时间后清除Woocommerce购物车。我需要在30分钟后重置会话(用例:购物车被丢弃)。
尝试使用Woocommerce购物车过期插件,但它不工作的最后一个版本的Woocommerce 5.7.1 Woocommerce购物车过期
也尝试过通过过滤器(粘贴在functions.php中),但它没有完成工作:
add_filter('wc_session_expiring', 'so_26545001_filter_session_expiring' );
function so_26545001_filter_session_expiring($seconds) {
return 60 * 25; // 25 mins
}
add_filter('wc_session_expiration', 'so_26545001_filter_session_expired' );
function so_26545001_filter_session_expired($seconds) {
return 60 * 30; // 30 mins
}
你可以试试-
// Start session if not started
add_action('init', 'register_my_session');
function register_my_session(){
if( !session_id() ) {
session_start();
}
}
// Clear cart after 30 minutes
add_action( 'init', 'woocommerce_clear_cart' );
function woocommerce_clear_cart()
{
global $woocommerce;
$current_time = date( 'Y-m-d H:i:s');
$expiry_in_seconds = 1800; // 30 minutes
if (!isset($_SESSION['active_time']))
{
$_SESSION['active_time'] = date('Y-m-d H:i:s');
}
else{
// add 30 minutes
$cart_expiry_time = strtotime($_SESSION['active_time']) + $expiry_in_seconds;
// calculate seconds left
$diff = $cart_expiry_time - strtotime($current_time);
// round to minutes
$remaining_minutes = floor($diff/60);
// if time less than or equal to 1 minutes
if($remaining_minutes<=1)
{
//if (isset($_GET['clear-cart']) && $_GET['clear-cart'] == 1)
{
$woocommerce->cart->empty_cart();
//WC()->session->set('cart', array());
//}
}
}
}
最佳方法:您应该设置一个cron作业并相应地每10分钟运行一次。如果您希望在cronjob中使用相同的功能,请取消注释,并像这样增加剩余时间:
if($remaining_minutes<=15){
if (isset($_GET['clear-cart']) && $_GET['clear-cart'] == 1) {
$woocommerce->cart->empty_cart();
//WC()->session->set('cart', array());
}
}
,并添加URL:
https://example.com?clear-cart=1//您的完整网站域名与参数?clear-cart=1