WordPress WooCommerce - Add a variable product to cart using the WC_Cart class

Both the above example actually work fine, they just don't display correctly in WooCommerce's own cart.

To make them display correctly, pass in an array for the forth parameter which seems to represent the variation in WooCommerce's own cart:

$arr = array();
$arr['Color'] = 'Green';
$woocommerce->cart->add_to_cart( 24, 1, 28, $arr, null ); 

For anyone else attempting something similar, here is my approach.

I created a script to be called via ajax that contains the following:

<?php
require_once("../../../wp-blog-header.php");
header("HTTP/1.1 200 OK");
global $woocommerce;

$quantity       = (isset($_REQUEST['qty'])) ? (int) $_REQUEST['qty'] : 1;
$product_id     = (int) apply_filters('woocommerce_add_to_cart_product_id', $_REQUEST['pid']);   
$vid            = (int) apply_filters('woocommerce_add_to_cart_product_id', $_REQUEST['vid']);   

if ($vid > 0) $woocommerce->cart->add_to_cart( $product_id, $quantity, $vid );         
else $woocommerce->cart->add_to_cart( $product_id, $quantity );    

This successfully adds product variations to the cart

Tags:

Php

Wordpress