php - 在 WooCommerce 中 72 小时后清空用户的购物车而不将其注销
问题描述
我试图在 72 小时不活动后以编程方式清空用户的购物车。有没有办法找出购物车上次更新的时间?
我试图提取购物车变量的转储,但我无法在任何地方找到指示用户最后一次在其中添加内容的时间戳。
不想为此使用插件!
解决方案
每次将产品添加到购物车时,以下代码都会将时间戳设置为自定义购物车商品数据:
// 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 文件中。测试和工作。
推荐阅读
- r - 提高循环需要多个数据帧作为参数的用户定义函数时的效率
- javascript - Java代码正在通过硒打开Chrome URL但是无法单击按钮
- laravel - Laravel 与 Slack 集成的未知状态
- ios - iOS 企业应用程序在 iOS 12 上崩溃
- r - GGPLOT:如何在百分比图上显示总数
- jquery - 如何将主入口文件路径移动到index.json?
- reactjs - 错误:请求失败,状态码 405
- django - django ORM 将相关表上的两个条件转换为两个单独的 JOIN
- mysql - 使用特定格式查询字段
- wordpress - algolia wordpress 自动完成