首页 > 解决方案 > 在 WooCommerce 中 72 小时后清空用户的购物车而不将其注销

问题描述

我试图在 72 小时不活动后以编程方式清空用户的购物车。有没有办法找出购物车上次更新的时间?

我试图提取购物车变量的转储,但我无法在任何地方找到指示用户最后一次在其中添加内容的时间戳。

不想为此使用插件!

标签: phpwordpressdatetimewoocommercecart

解决方案


每次将产品添加到购物车时,以下代码都会将时间戳设置为自定义购物车商品数据:

// 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 文件中。测试和工作。


推荐阅读