Written on 4. November 2021 by Lennart Christensen

Add cart_item_data with $woocommerce->cart->add_to_cart

There are 5 arguments for the add_to_cart method in the WC_Cart class.

  • $product_id
    ( int ) optional - contains the id of the product to add to the cart.
  • $quantity
    ( int ) optional default: 1 - contains the quantity of the item to add.
  • $variation_id
    ( int ) optional - ID of the variation being added to the cart.
  • 1TP3Variation
    ( array ) optional - attribute values.
  • $cart_item_data
    ( array ) optional - extra cart item data we want to pass into the item.

Here in my example my goal was to work with simple products and use attributes so the user can choose size without the product having to be set as a variable product. An example of how to add a product to the basket that is not a variation:

$cart_item_data['size'] = array('size'=>$variation_id);
$woocommerce->cart->add_to_cart( $product_id, $quantity, NULL, $cart_item_data);

Then you can work with the data as you like. You can save the data and display it on the order in woo like this:

add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_data_as_order_item_meta_data', 20, 4 );
function save_cart_item_data_as_order_item_meta_data( $item, $cart_item_key, $values, $order ) {
	if ( isset( $values['size'] ) ) {
		foreach ( $values['size'] as $key => $attribute ) {
			$item->update_meta_data( __( 'size'), $attribute );
		}
	}
}