Here’s the situtation: you’d like to update the meta data for items that have already been added to the cart. Updating meta data before or as an item is added to the cart is simple, you’d use theĀ woocommerce_add_cart_item_data filter. But to update items that are already in the cart is trickier. Here’s how:

<?php
function prefix_update_existing_cart_item_meta() {
$cart = WC()->cart->cart_contents;
foreach( $cart as $cart_item_id=>$cart_item ) {
$cart_item['new_meta_data'] = 'Your stuff goes here';
WC()->cart->cart_contents[$cart_item_id] = $cart_item;
}
WC()->cart->set_session();
}

First, you get the contents of the cart then you iterate through each item. Amend or add the meta data as required, then update the cart item using the cart item key.

When you’ve finished, you need to reset the WooCommerce session with the updated data.

That’s it.


Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *