Using checkboxes for variations in WooCommerce to allow multiple choice

Michael Emerson picture Michael Emerson · Nov 17, 2016 · Viewed 11.3k times · Source

I've been using WooCommerce for a while now but this one issue is causing me a problem. The client I'm making a site for provides training courses and presentations, and this partiular product (or presentation) allows several different options to be added to the cart, each with its own price.

So, the base price is zero. Then there are 8 different presentations that the user can select via checkbox on their existing website - I somehow need to replicate that using WooCommerce on their new site but I can only use drop downs for variations, and as far as I can see it only allows one option to be chosen. The only feasible way I can see this working is if I add 8 different dropdowns each with all 8 presentations within them and then the customer selects however many different ones they want. This is a bit cumbersome though and potentially can cause user error (selecting the same presentation twice for example).

I have attached a screenshot of what I'd ideally like it to look like within WooCommerce, is there a way this is achievable? I don't mind using plugins if it's the only way.

enter image description here

Answer

Jiri Kral picture Jiri Kral · Nov 17, 2016

You can do it this way:

1) Edit you content-single-product.php:

2) Get product by $product = wc_get_product( $productId )

3) Check if $product->product_type == "variable"

4) Get all variants of current product and list it to checkboxes:

$variations = $product->get_available_variations();

foreach ( $variations as $variation ) {

$variationId = $variation['variation_id'];

echo '<input type="checkbox" name="variations[]" value="' . $variationId . '" />

}

echo '<input type="checkbox" name="product_id" value="' . $product->ID . '" />

5) After that you can process $_POST and add variations to cart programatically:

if ( !empty( $_POST['variations'] ) ) {

$productId = $_POST['product_id'];
$qty = 1;
$buyVariations = $_POST['variations'];

foreach ( $buyVariations as $variationId ) {

WC()->cart->add_to_cart( $productId, $qty, $variationId );

}

}

6) Sanitization, validation and status messaging is on you, but this process should works.