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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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.
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?
This is how WooCommerce saves cart data.
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;
}
WC()->cart->set_session();
Hi – when you say it’s not working, are you getting an error message?
Where would be the safest place to call this function?
Thanks!
Hi Allixria
Here’s how to add a snippet to your site: https://pluginrepublic.com/documentation/how-to-add-a-code-snippet-to-your-site/
Thanks
Gareth
Hi Gareth,
I think she didn’t mean how to add a snippet to her site, but which filter or action to use to trigger this function. At least, that would be my question. 😉
Thanks a lot for all your work!
Ben