cookies - 在 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 的?
我就是想不通。
任何帮助将不胜感激。
解决方案
我会以不同的方式处理它。首先清空用户购物车,然后添加所有产品。就像是:
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']);
}
}
我没有测试过,但总的来说,我认为这比强制会话更好
推荐阅读
- dbeaver - Dbeaver:在导航器中找不到数据库
- python - 如何在过滤 Django 模型时创建 OR 条件?
- python - 将 numpy 方程转换为 Keras 后端损失函数方程
- arrays - 如何将数组添加到 Firebase Firestore Swift
- android - RxJava 返回错误为 onNext 并继续流
- git - 如何克服 git 上的身份验证失败错误?
- c - 定义一个结构后,typedef那个结构
- python - 将 np.append 与二维数组一起使用时遇到问题
- mysql - 锁定共享模式和更新,而不是 MariaDB 中的任何内容
- c# - 将一个模型从 ViewModel 发送回控制器