Answer the question
In order to leave comments, you need to log in
How to make different gifts for different basket amounts?
Good day! There was such a question, how can you make sure that with a different amount of the basket, there are different gifts for them? Suppose there was one gift for the basket amount >= 1000 rubles, from 1500 or more another gift (if before that there was a gift for 1000 rubles in the basket, it would be removed from the basket and instead it would be added for 1500). Can you suggest? I myself relied on the official documentation -> https://woocommerce.com/document/automatically-add... . And at the moment I was able to write the code, only for the amount of 1000 rubles (it is given below).
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 4548; //айди подарка
$found = false;
$cart_total = 1000; //сумма корзины
$is_gift_in_cart = $woocommerce->cart->find_product_in_cart( $woocommerce->cart->generate_cart_id( $product_id ) );// проверка есть ли подарок в корзине
if( $woocommerce->cart->total >= $cart_total ) {
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
} else {
$woocommerce->cart->add_to_cart( $product_id );
}
}
if($woocommerce->cart->total < $cart_total){// если сумма заказа меньше
if($is_gift_in_cart){
$woocommerce->cart->remove_cart_item( $woocommerce->cart->generate_cart_id( $product_id ) );// убираем подарок
}
}
}
}
Answer the question
In order to leave comments, you need to log in
I may not have fully understood the problem (I didn’t specifically work with woocommerce), but your code simply doesn’t specify the conditions for the amount from 1500... Write it like this:
// условие: сумма от 1000 до 1499
if ($woocommerce->cart->total >= $cart_total
&& $woocommerce->cart->total <= 1499) {
if (sizeof($woocommerce->cart->get_cart()) > 0) {
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->get_id() == $product_id)
$found = true;
}
if (!$found)
$woocommerce->cart->add_to_cart($product_id);
} else {
$woocommerce->cart->add_to_cart($product_id);
}
} elseif ($woocommerce->cart->total >= 1500) { // условие: сумма от 1500
/* ... */
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question