-
AuthorPosts
-
September 26, 2022 at 7:49 am #139222
David WurmanParticipantI have this code that works ok, but when I change the currency it does not take the calculation of the subtotal of the currency by default, which would be USD.
add_action( ‘woocommerce_before_calculate_totals’, ‘add_free_product_to_cart’ );
function add_free_product_to_cart( $cart ) {
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) )
return;
global $woocommerce;
$total_nuevo = $woocommerce->cart->subtotal;
$free_product_id = 508; // <= Set the free product id to add
$min_subtotal = 99; // <= Set the minimum cart subtotal required
$has_shippable = $free_key = false; // Initializing
$cart_subtotal = 0;// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if free product is in cart
if ( $free_product_id == $cart_item[‘product_id’] ) {
$free_key = $cart_item_key;
$free_qty = $cart_item[‘quantity’];
$cart_item[‘data’]->set_price(0); // Optional: Set free product price to zero
}// Check for non virtual products
if ( $cart_item[‘data’]->is_virtual() !== true ) {
$has_shippable = true;
}
// Calculate items subtotal: Add discounted Line total with taxes
$cart_subtotal += $cart_item[‘line_total’] + $cart_item[‘line_tax’];
}// Add Free product
if ( $amount >= $min_subtotal && $has_shippable && $free_key === false ) {
$cart->add_to_cart( $free_product_id, 1 );
}
// Remove free product
elseif ( ( $cart_subtotal < $min_subtotal ) && $free_key !== false ) {
$cart->remove_cart_item( $free_key );
}
// Adjust free product quantity to 1
elseif ( $free_key !== false && $free_qty > 1 ) {
$cart->set_quantity( $free_key, 1 );
}
}Attachments:
You must be logged in to view attached files. -
AuthorPosts
You must be logged in to see replies to this topic. Click here to login or register