Add cart_item_data with $woocommerce->cart->add_to_cart

Der er 5 argumenter for add_to_cart metoden i WC_Cart klassen.

  • $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.
  • $variation
    ( array ) optional – attribute values.
  • $cart_item_data
    ( array ) optional – extra cart item data we want to pass into the item.

Her er i mit eksempel var mit mål at arbejde med simple produkter og bruge attributer så brugeren kan vælge størrelse uden at produktet skulle indstilles som et variabel produkt. Et eksempel på, hvordan du tilføjer et produkt til kurven som ikke er en variation:

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

Herefter kan man arbejde med det data som man vil. Du kan gemme dataen og vise det på ordren i woo sådan her:

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 );
		}
	}
}
Skærmbillede fra en ordre i WooCommerce med size attribut tilføjet på et single produkt type.