I used some code I found to try and update the Woocommerce cart for specific items. The update is taking place via an AJAX call (which I think is irrelevant). Ajax returns successfully every time, but around half the time, the custom data is not updated, but just wiped to null (even though AJAX returns the correct date). This makes me think that the Woocommerce cart function is working only sometimes for some reason. Please help me find out why.
The action should be taking place at the $woocommerce->cart->set_session(); code.
Code that runs to update WC cart:
<?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));
}