There may be instances where you want to add additional data whenever a product is added to the cart. This additional data could be the file selected while adding a product to the cart as we do in the case of WooCommerce Addon Uploads Pro. In such cases, the best place to store the data for further processing would be Cart Item Meta.
Adding cart item meta
To add cart item meta the best filter which WooCommerce provides is woocommerce_add_cart_item_data
. This filter is triggered when an add to cart action is triggered. Let’s understand the parameters available with this filter. The filter description is:
apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id );
The cart item data is the object that will hold the custom data that is being passed during an add to cart operation.
Example usage of the filter is as below:
function img_sol_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
$cart_item_data['meta1'] = $_POST['meta1'];
$cart_item_data['meta2'] = $_POST['meta2'];
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'img_sol_add_cart_item_data', 99, 3 );
Updating Existing Cart Meta Data
Now that you have added custom meta data to your items added to the cart, what if you want to update the value of this meta data?
A typical use case for this could be allowing users to edit some of the options while on the cart page. In that case you can use the below function to alter your WooCommerce Cart Item Meta data values:
function prefix_update_existing_cart_item_meta() {
$cart = WC()->cart->cart_contents;
foreach( $cart as $cart_item_id=>$cart_item ) {
$cart_item['meta1'] = 'New value to be updated';
WC()->cart->cart_contents[ $cart_item_id ] = $cart_item;
}
WC()->cart->set_session();
}
In the above code snippet, we are getting the WooCommerce cart contents using cart_contents
property. We then loop through each item and update the cart item meta.
Please note that the entire cart item present in $cart_item
object needs to be updated back.
The final save happens using set_session
function on the WooCommerce Cart object.
Please let me know in the comments below if the code is functioning fine for you or not or if you are facing any errors.