I’m currently adding a product to the shopping cart like this:
$woocommerce->cart->add_to_cart( $product_id, $quantity );
I’ve noticed the add_to_cart()
method actually accepts 5 parameters. See the following (taken from the WooCommerce docs):
add_to_cart( string $product_id, string $quantity = 1, integer $variation_id = '', array $variation = '', array $cart_item_data = array() )
Can someone give an example what the last 3 parameters would be used for?
$variation_id
$variation
$cart_item_data
[An array containing any other cart item data for this product.]
There is some description of what these are in the method documentation but it isn’t hugely explanatory:
int $variation_id
array $variation attribute values
array $cart_item_data extra cart item data we want to pass into the item
Ref: http://docs.woothemes.com/wc-apidocs/class-WC_Cart.html#_add_to_cart
For the last 3 parameters, you can use them like so:
$variation_id
: This would be the specific post ID of the variation, if the product is a variation. If the product you’re adding is a simple product or not a variable product, you can leave this blank or set it to 0.$variation
: When you select a variation of a variable product, this array contains what the variation attributes are and what values the customer selected.$cart_item_data
: This is an array of data that allows you to store custom data to the product in your cart. For example, if you wanted to store some meta data about the product that would be useful later on, you can add it here. It will then be available when you loop over your cart items.Here’s an example from a snippet of code I wrote for a plugin: