【发布时间】:2020-09-29 16:05:14
【问题描述】:
我正在尝试在 72 小时不活动后以编程方式清空用户的购物车。有没有办法查出购物车上次更新的时间?
我试图提取购物车变量的转储,但在任何地方都找不到指示用户最后一次在其中添加内容的时间戳。
不想为此使用插件!
【问题讨论】:
标签: php wordpress datetime woocommerce cart
我正在尝试在 72 小时不活动后以编程方式清空用户的购物车。有没有办法查出购物车上次更新的时间?
我试图提取购物车变量的转储,但在任何地方都找不到指示用户最后一次在其中添加内容的时间戳。
不想为此使用插件!
【问题讨论】:
标签: php wordpress datetime woocommerce cart
以下代码将在每次将产品添加到购物车时将时间戳设置为自定义购物车商品数据:
// Set current date time as custom item data
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data_timestamp', 10, 3 );
function add_cart_item_data_timestamp( $cart_item_data, $product_id, $variation_id ) {
// Set the shop time zone (List of Supported Timezones: https://www.php.net/manual/en/timezones.php)
date_default_timezone_set( 'Europe/Paris' );
$cart_item_data['timestamp'] = strtotime( date('Y-m-d h:i:s') );
return $cart_item_data;
}
然后,当最后一次添加的商品在 72 小时后添加时,以下钩子函数将清空购物车:
// Empty cart after 3 days
add_filter( 'template_redirect', 'empty_cart_after_3_days' );
function empty_cart_after_3_days(){
if ( WC()->cart->is_empty() ) return; // Exit
// Set the shop time zone (List of Supported Timezones: https://www.php.net/manual/en/timezones.php)
date_default_timezone_set( 'Europe/Paris' );
// Set the threshold time in seconds (3 days in seconds)
$threshold_time = 3 * 24 * 60 * 60;
$threshold_time = 1 * 60 * 60;
$cart_items = WC()->cart->get_cart(); // get cart items
$cart_items_keys = array_keys($cart_items); // get cart items keys array
$last_item = end($cart_items); // Last cart item
$last_item_key = end($cart_items_keys); // Last cart item key
$now_timestamp = strtotime( date('Y-m-d h:i:s') ); // Now date time
if( isset($last_item['timestamp']) && ( $now_timestamp - $last_item['timestamp'] ) >= $threshold_time ) {
WC()->cart->empty_cart(); // Empty cart
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。
【讨论】: