How to update existing WooCommerce cart meta data

Change the meta data for items that have already been added to the cart

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.

If you’d like to know more about adding custom item meta data to the WooCommerce cart, check out this article.


Popular Posts

2 thoughts on “How to update existing WooCommerce cart meta data

this is great, but one more question, why have you not explained what would we need to do in case we have not used sessions to store data?

Reply

This is how WooCommerce saves cart data.

Reply

Leave a Reply

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