This product can cost zero and so make it a gift
function maybe_handle_gift_product() {
$gift_product_id = 3444;
$threshold = 60;
$cart = WC()->cart;
if ( is_admin() || ! $cart ) return;
$cart_total = $cart->get_subtotal() + $cart->get_discount_total();
$gift_in_cart = false;
$gift_key = '';
foreach ( $cart->get_cart() as $key => $item ) {
if ( $item['product_id'] == $gift_product_id ) {
$gift_in_cart = true;
$gift_key = $key;
break;
}
}
if ( $cart_total >= $threshold ) {
if ( ! $gift_in_cart ) {
$cart->add_to_cart( $gift_product_id, 1, 0, [], [ 'is_auto_gift' => true ] );
}
} else {
if ( $gift_in_cart ) {
$cart->remove_cart_item( $gift_key );
}
}
}
add_action( 'woocommerce_cart_updated', 'maybe_handle_gift_product' );
function prevent_manual_gift_product_addition( $passed, $product_id, $quantity, $variation_id = null, $variations = null, $cart_item_data = [] ) {
if ( $product_id == 3444 && empty( $cart_item_data['is_auto_gift'] ) ) {
wc_add_notice( 'Αυτό το προϊόν δεν μπορεί να προστεθεί στο καλάθι χειροκίνητα.', 'error' );
return false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'prevent_manual_gift_product_addition', 10, 6 );
Was this helpful?
YesNo