Using checkboxes for variations in WooCommerce to allow multiple choice

我怕爱的太早我们不能终老 提交于 2019-12-05 02:02:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40661032/using-checkboxes-for-variations-in-woocommerce-to-allow-multiple-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!