How to use the add_to_cart() method in WooCommerce?

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):

Read More
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

Related posts

Leave a Reply

1 comment

  1. 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:

    $gift_item = wc_get_product($gift_item_id);
    $gift_variation_id = 0;
    $variation_data    = [];
    // The Gift is a variation, so get the variation options that are associated with this product variation.
    if ($gift_item->is_type('variation')) {
        $gift_variation_id = $gift_item->get_id();
        $variation_data    = wc_get_product_variation_attributes($gift_variation_id);              
    }
    
    //Check to see if the product is already in our cart and has an item meta of being a gift item
    $gift_item_hash = $cart->generate_cart_id($gift_item->get_parent_id() ?: $gift_item->get_id(), $gift_variation_id, $variation_data, [
        'gift'     => true
    ]);
    
    if ($cart->find_product_in_cart($gift_item_hash) === false) {
        // Add the Gift to our cart. Add some meta data to the item so we can change it's price at checkout.
        $gift_cart_item_key = $cart->add_to_cart($gift_item_id, $new_gift_quantity, $gift_variation_id, $variation_data, ['gift' => true]);
    }