Z
Z
z1mak2016-10-28 12:29:54
WordPress
z1mak, 2016-10-28 12:29:54

How to allow purchase only by packages in WooCommerce?

Hello, I came across this example, but unfortunately it does not work with the latest versions of WooCommerce.
Therefore, I want to ask what needs to be changed in order for it to work correctly.
We only allow buying packages in WooCommerce
2014-06-03 | AmoSeo
Let's imagine that you run a WooCommerce store where you sell products that come in boxes, and you want customers to create their own "boxes" with various products, while WooCommerce by default allows you to sell products in the quantity that you have set for this product (for example, 1pc), and the buyer can choose any quantity of the product in his cart.
For example, if you have an online WooCommerce wine store and would like to sell your wine by one bottle, but only on the condition that the customer purchases enough bottles to form a whole box, then this article is for you.
With the code below, you can specify for your items that each item is one bottle of wine, and then force the customer to add a different 6 items to the cart before payment is available. If a customer, for example, adds only 5 bottles to their cart and then tries to pay, they will be notified that they need to buy 6 bottles.
4b16a75a3b17435fa21000dc2318f1b1.png
Allow purchase only by packages in WooCommerce
You can even implement this rule for products with a certain delivery class, which will allow you to sell bottles individually, and at the same time 6 pieces, the main thing is to correctly distinguish everything.
To force a customer to add a certain amount of an item to their cart before payment is available, add the following code to your theme's functions.php file or WordPress plugin:

<?php

 
// Ограничиваем товары в корзине определенным классом доставки для покупки "целым ящиком"
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities_for_class' );
function woocommerce_check_cart_quantities_for_class() {
global $woocommerce;
$multiples = 6;
$class = 'bottle';
$total_products = 0;
  foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $product = get_product( $values['product_id'] );
    if ( $product->get_shipping_class() == $class ) {
      $total_products += $values['quantity'];
    }
  }
if ( ( $total_products % $multiples ) > 0 )
$woocommerce->add_error( sprintf( __('Вам необходимо купить бутылок в количестве %s', 'woocommerce'), $multiples ) );
}
?>

Example Source

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Petrovsky, 2016-10-29
@Redjek

Try WooCommerce Advanced Product Quantities , there was a plug-in somewhere that gives you, individually for each product, how many products you can buy per order.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question