php - Woocommerce 购物车有时仅使用 PHP 功能更新
问题描述
我使用了一些我发现的代码来尝试更新特定商品的 Woocommerce 购物车。更新是通过 AJAX 调用进行的(我认为这无关紧要)。Ajax 每次都成功返回,但大约有一半的时间,自定义数据没有更新,而只是擦除为 null(即使 AJAX 返回正确的日期)。这让我觉得 Woocommerce 购物车功能有时出于某种原因才起作用。请帮我找出原因。
该操作应在$woocommerce->cart->set_session();
代码处进行。
运行以更新 WC 购物车的代码:
<?php
// This function is included in functions.php
// Update dates of all weekly quantity products in cart to match each other. (This is used for when user opts to match all their product dates)
// Add action to ajax function that is created from ajax call
add_action('wp_ajax_update_weekly_quantity_products_dates', 'update_cart_product_weekly_quantity_date');
add_action( 'wp_ajax_nopriv_update_weekly_quantity_products_dates', 'update_cart_product_weekly_quantity_date' );
function update_cart_product_weekly_quantity_date () {
if (isset( $_POST['date_week'] )) {
// $_POST['date_week'] comes to us an an epoch number. We format it to d-m-Y below.
$newDate = date('d-m-Y', $_POST['date_week']);
// Loop through cart items,change date of each
$cart_items = [];
$cart = WC()->cart->get_cart();
foreach( $cart as $cart_item_key=>$cart_item ) {
global $woocommerce;
$woocommerce->cart->cart_contents[$cart_item_key]['custom_data']['pickup_week'] = $newDate;
$woocommerce->cart->cart_contents[$cart_item_key]['custom_data']['pickup_day_of_week'] = $newDate;
$woocommerce->cart->set_session(); // when in ajax calls, saves it.
}
}
$formattedDate = date('D, M j Y', strtotime($newDate));
// Exit and return response message to frontend
die('Dates updated to '. $formattedDate. ' cart items:' . var_dump($cart_items));
}
解决方案
推荐阅读
- python - 在 python jupytr notebook 中显示输出时,我得到了“绑定方法 NDFrame.head”
- javascript - React 的 useEffect 和 DOM 事件处理程序之间的执行顺序
- node.js - 拖放后如何更新记录
- python - 如何使用 for 循环比较 Python 中的两个列表?
- java - 二维数组转换(整数到字符串)
- python - 连续的 ipywidgets 按钮
- windows - 如何使 Windows 文件资源管理器在图块中从上到下而不是从左到右显示文件`
- python - 涉及列表操作的 Python 函数的时间复杂度
- log4net - log4net 没有将精确时间记录到数据库
- mysql - AWS Lambda 函数返回方括号“[]”结果