How to update existing WooCommerce cart meta data

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:

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;

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.

Six comments

  1. 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?

  2. Hi Gareth,

    I’ve tried to use the same analogy to change a product price in cart but it is not working, is it something related to wordpress new version or my code?

    $cart = WC()->cart->get_cart_contents();
    foreach( $cart as $key => $value ) {
    $value[‘data’]->name = $value[‘data’]->name . ‘ – Paid ‘ . $term;
    $value[‘data’]->set_price = $cost/$users;
    WC()->cart->cart_contents[$key] = $value;

Leave a Reply

Your email address will not be published. All fields are required.