首页 > 解决方案 > 在 Ajax woocommerce 期间更改购物车数据

问题描述

在 Ajax 期间,我正在尝试用保存的购物车替换当前的 WooCommerce 购物车。

这是我正在使用的代码:

function restore()
{
    $current_user_id = get_current_user_id();
    if ($current_user_id > 0) {
        if (function_exists('get_user_attribute')) {

            $buy_now_persistent_cart = get_user_meta($current_user_id, '_buy_now_persistent_cart', true);
            error_log(print_r($buy_now_persistent_cart, 1));

        if (!empty($buy_now_persistent_cart['cart'])) {
            WC()->session->cart            = $buy_now_persistent_cart['cart'];
            WC()->session->applied_coupons = $buy_now_persistent_cart['applied_coupons'];
            if (function_exists('delete_user_attribute')) {
                //delete_user_attribute( $current_user_id, '_buy_now_persistent_cart' );
            }
            //delete_user_meta( $current_user_id, '_buy_now_persistent_cart' );
        }
    }
}

这是 $buy_now_persistent_cart 输出:

Array
(
    [cart] => Array
        (
            [3430dcf4efe8aa0c418434656773a73a] => Array
                (
                    [key] => 3430dcf4efe8aa0c418434656773a73a
                    [product_id] => 126096
                    [variation_id] => 0
                    [variation] => Array
                        (
                        )

                    [quantity] => 1
                    [data_hash] => b5c1d5ca8bae6d4896cf1807cdf763f0
                    [line_tax_data] => Array
                        (
                            [subtotal] => Array
                                (
                                )

                            [total] => Array
                                (
                                )

                        )

                    [line_subtotal] => 2.4
                    [line_subtotal_tax] => 0
                    [line_total] => 2.4
                    [line_tax] => 0
                )

        )

    [applied_coupons] => Array
        (
        )

)

当我在设置新数据后输出 WC()->session->cart 时,它似乎已正确更改,但是当 Ajax 完成时更新的购物车不存在。

我想这是关于保存购物车和/或设置购物车哈希和 cookie 的?

我就是想不通。

任何帮助将不胜感激。

标签: cookieswoocommerce

解决方案


我会以不同的方式处理它。首先清空用户购物车,然后添加所有产品。就像是:

if (!empty($buy_now_persistent_cart['cart'])) {
   WC()->cart->empty_cart();
   foreach($buy_now_persistent_cart['cart'] as $item){
      WC()->cart->add_to_cart($item['product_id'], $item['quantity']);
   }
}

我没有测试过,但总的来说,我认为这比强制会话更好


推荐阅读