using the code found on Internet, works perfectly, but it needs to be updated with extra function.
now: if total sum gets 100+ free gift is added. if user removes some products and total gets lower than 100, free gift still stays there
should be: if user removes products and total gets lower than 100, free gift is removed
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 100;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin() ) {
$free_product_id = 6663; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
this works
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users (and avoiding the hook repetition)
if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 99.9; // The threshold amount for cart total
$free_product_id = 6663; // ID of the free product
$cart_items_total = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( $cart_item['data']->get_id() == $free_product_id ) {
$free_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If Cart total is up to the defined amount and if the free products is not in cart, we add it.
if ( $cart_items_total >= $threshold_amount && ! isset($free_item_key) ) {
$cart->add_to_cart( $free_product_id );
}
// If cart total is below the defined amount and free product is in cart, we remove it.
elseif ( $cart_items_total remove_cart_item( $free_item_key );
}
}
Related
I am on a project, which needs to add to cart a free item on particular promotional month. Therefore, I need to make the product value 0.00 and add it automatically to cart in a particular promotional month. So far, I have added the product automatically when the add to cart total reaches certain amount
/*
* Automatically adding the product to the cart when cart total amount reach to $500.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 500;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin() ) {
$free_product_id = 12989; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
...
Try the following instead (that handle dynamic changes in cart page and also a month range).
Note: the total amount for the threshold can be only the cart items total.
The code:
function is_free_product_allowed_for_month() {
// Define allowed months in the array (values from 1 to 12)
$allowed_months = array('3', '7', '8');
return in_array( date('n'), $allowed_months );
}
add_action( 'woocommerce_before_calculate_totals', 'add_remove_free_product' );
function add_remove_free_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Check if we are in an allowed month
if ( ! is_free_product_allowed_for_month() )
return;
$free_product_id = 339; // ID of the free product
$threshold_amount = 200; // The threshold amount for cart subtotal
$cart_items_total = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( in_array( $free_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
$cart_item['data']->set_price(0); // Set price to Zero
$free_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If Cart total is up to the defined amount and if the free products is not in cart, we add it.
if ( $cart_items_total >= $threshold_amount && ! isset($free_item_key) ) {
$cart->add_to_cart( $free_product_id );
}
// If cart total is below the defined amount and free product is in cart, we remove it.
elseif ( $cart_items_total < $threshold_amount && isset($free_item_key) ) {
$cart->remove_cart_item( $free_item_key );
}
}
// For minicart displayed free product price
add_filter( 'woocommerce_cart_item_price', 'free_product_cart_item_price', 10, 3 );
function free_product_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
// Check if we are in an allowed month
if ( ! is_free_product_allowed_for_month() )
return $price_html;
$free_product_id = 339; // ID of the free product
if ( in_array( $free_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
return wc_price( 0 );
}
return $price_html;
}
Code goes in functions.php file of the active child theme (or active theme). It should work.
Related: Add or remove specific cart Item based on WooCommerce cart total
I'm trying to create code that automatically adds an item to the customer's cart once they reach a particular price point in the cart. AND I'm trying to exclude that from happening if they are only ordering virtual products, as the "free gift" is only meant for products that are being shipped out. The code I'm using is adding the free gift at the right dollar amount, but it's not excluding any virtual product. Can anyone id what I'm doing wrong?
Here's the code:
/**
* Add another product depending on the cart total
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 85942; //replace with your product id
$found = false;
$cart_total = 15; //replace with your cart total needed to add above item
if( $woocommerce->cart->total >= $cart_total ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
$isVirtualOnly = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values[‘data’];
if ($_product != null)
if ($_product->get_type() != $_virtual)
$isVirtualOnly = false;
}
if ($isVirtualOnly != true) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
}
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
/**
* END Add another product depending on the cart total
*/
Updated: The following will auto add to cart a free product:
if there is at least a shippable item in cart,
if the free product is not in cart yet,
and if the cart subtotal is not below a specific amount.
Or will remove the fee product from cart:
if the cart subtotal is not below a specific amount,
and if there is only virtual products.
The code:
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;
$free_product_id = 38; // <= Set the free product id to add
$min_subtotal = 80; // <= 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 ( $cart_subtotal >= $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 );
}
}
// Optional: Display free product price to zero on minicart
add_filter( 'woocommerce_cart_item_price', 'change_minicart_free_gifted_item_price', 10, 3 );
function change_minicart_free_gifted_item_price( $price_html, $cart_item, $cart_item_key ) {
$free_product_id = 38;
if( $cart_item['product_id'] == $free_product_id ) {
return wc_price( 0 );
}
return $price_html;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related:
Free Give-Away product for specific cart subtotal in WooCommerce
Add free gifted product for a minimal cart amount in WooCommerce
I want to give customers with orders above $50 a free gift. Not if a specific product is in the cart (there are some examples here on stackoverflow and below).
After some research I found the following code to add a free product if another specific product is added to the cart.
add_action( 'template_redirect', 'bbloomer_add_gift_if_id_in_cart' );
function bbloomer_add_gift_if_id_in_cart() {
if ( is_admin() ) return;
if ( WC()->cart->is_empty() ) return;
$product_bought_id = 32;
$product_gifted_id = 57;
// see if product id in cart
$product_bought_cart_id = WC()->cart->generate_cart_id( $product_bought_id );
$product_bought_in_cart = WC()->cart->find_product_in_cart( $product_bought_cart_id );
// see if gift id in cart
$product_gifted_cart_id = WC()->cart->generate_cart_id( $product_gifted_id );
$product_gifted_in_cart = WC()->cart->find_product_in_cart( $product_gifted_cart_id );
// if not in cart remove gift, else add gift
if ( ! $product_bought_in_cart ) {
if ( $product_gifted_in_cart ) WC()->cart->remove_cart_item( $product_gifted_in_cart );
} else {
if ( ! $product_gifted_in_cart ) WC()->cart->add_to_cart( $product_gifted_id );
}
}
Found here: https://www.businessbloomer.com/woocommerce-buy-1-product-add-free-product-cart-programmatically/
I also tried this code but it doesn't update if the cart changes:
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 50;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin() ) {
$free_product_id = 12989; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
Is there any way to change that code to work with any product and limit only to the cart total?
Updated
With the following, a free gifted product will be added to cart if subtotal is up to a specific amount:
// Add free gifted product for specific cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$free_product_id = 37;
$targeted_subtotal = 50;
$cart_subtotal = 0; // Initializing
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// When free product is is 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); // Optionally set the price to zero
} else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// If subtotal match and free product is not already in cart, add it
if ( ! isset($free_key) && $cart_subtotal >= $targeted_subtotal ) {
$cart->add_to_cart( $free_product_id );
}
// If subtotal doesn't match and free product is already in cart, remove it
elseif ( isset($free_key) && $cart_subtotal < $targeted_subtotal ) {
$cart->remove_cart_item( $free_key );
}
// Keep free product quantity to 1.
elseif ( isset($free_qty) && $free_qty > 1 ) {
$cart->set_quantity( $free_key, 1 );
}
}
// Display free gifted product price to zero on minicart
add_filter( 'woocommerce_cart_item_price', 'change_minicart_free_gifted_item_price', 10, 3 );
function change_minicart_free_gifted_item_price( $price_html, $cart_item, $cart_item_key ) {
$free_product_id = 27;
if( $cart_item['product_id'] == $free_product_id ) {
return wc_price( 0 );
}
return $price_html;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
On cart page (the free gifted product is "Beanie"):
On mini cart:
I'm trying to create a discount programmatically for orders on my store. My users have a variable discount rate e.g. 10%. I want to apply their discount to the order before checkout, however, some items in the store are not applicable for a discount.
These items have a toggle set so I can check which products do or do not allow the discount to be applied.
Currently, I'm looping through the order to check which items are applicable and using a 'fixed_cart'coupon to add the discount.
This works, however, the in the admin the coupon applies to all line items even the items which should be skipped. Making it impossible to work how much to refund to customers when a refund is required.
Checking the cart items
$tradeDiscountTotal = 0;
foreach( WC()->cart->get_cart() as $cart_item ) {
if(!get_field('trade_discount_exempt', $cart_item['product_id'])) {
$tradeDiscountTotal += $cart_item['line_subtotal'];
}
}
Applying the total discount for this order
$coupon->set_discount_type('fixed_cart');
$coupon->set_amount($tradeDiscountTotal);
return $coupon;
How can I create a bespoke discount for each order and ensure the products that are discounted are represented correctly in the admin area?
UPDATE
A solution is to create a coupon manually with a percentage discount with for example 10%.
Then we add the following codes based on the couponcode
First part to ensure that a discount of 0 is applied to products that meet the condition
Second part to ensure that the coupon is automatically added to the shopping cart
So we get:
Discount amount on trade_discount_exempt = 0
function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {
// Product ID in cart
$product_id = $cart_item['product_id'];
// If 'trade_discount_exempt'
if ( get_field( 'trade_discount_exempt', $product_id ) ) {
$discount = 0;
}
return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );
Apply coupon programmatically if NOT trade_discount_exempt in cart
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Only cart
if( ! is_cart() )
return;
// Coupon code
$coupon_code = 'testcoupon';
// Format
$coupon_code = wc_format_coupon_code( $coupon_code );
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Product ID in cart
$product_id = $cart_item['product_id'];
// NOT 'trade_discount_exempt'
if ( ! get_field( 'trade_discount_exempt', $product_id ) ) {
// Applied coupons
$applied_coupons = $cart->get_applied_coupons();
// Is applied
$is_applied = in_array( $coupon_code, $applied_coupons );
// NOT applied
if ( ! $is_applied ) {
// Apply
$cart->apply_coupon( $coupon_code );
break;
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
Optional: Here are 2 other possible solutions:
1. Use the woocommerce_calculated_total filter hook, apply a discount globally on cart
function filter_woocommerce_calculated_total( $total, $cart ) {
// Discount (percentage)
$percentage = 10; // 10 %
// Set variable, used in loop
$new_total = 0;
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Product ID in cart
$product_id = $cart_item['product_id'];
// NOT 'trade_discount_exempt'
if( ! get_field( 'trade_discount_exempt', $product_id ) ) {
// Product price
$price = $cart_item['data']->get_price();
// Caclulate new price
$new_price = $price * ( 1 - ( $percentage / 100 ) );
// Add new price to new total
$new_total += $new_price;
}
}
// New total greater than
if ( $new_total > 0 ) {
$total = $new_total;
}
return $total;
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );
2. Use the woocommerce_before_calculate_totals action hook, grant the discount on the product price
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Discount (percentage)
$percentage = 10; // 10 %
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Product ID in cart
$product_id = $cart_item['product_id'];
// NOT 'trade_discount_exempt'
if( ! get_field( 'trade_discount_exempt', $product_id ) ) {
// Product price
$price = $cart_item['data']->get_price();
// Caclulate new price
$new_price = $price * ( 1 - ( $percentage / 100 ) );
// Set price
$cart_item['data']->set_price( $new_price );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
I am trying to add a free product to the cart if the order total is above $199.99
I have achieved this and it is working. The issue is that I need to remove the product if the user then deletes an item from the cart and goes below $199.99 again (to prevent gaming the system).
What I have seems to be working. The problem is that it seems I need to click 2 links before the REMOVE FROM CART action seems to be working (or refresh the page).
What is causing this? Can the remove action be accomplished with AJAX by any chance?
// -------------------------------------------
// ADD PRODUCT IF ORDER MINIMUM ABOVE 200
/*
* Automatically adding the product to the cart when cart total amount reach to $199.99.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 199.99;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( is_user_logged_in() ) {
$free_product_id = 339; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
if ( $woocommerce->cart->total <= $cart_total && $found ) {
WC()->cart->remove_cart_item( $free_product_id );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
add_action( 'template_redirect', 'remove_product_from_cart_programmatically' );
function remove_product_from_cart_programmatically() {
if ( is_admin() ) return;
$product_id = 339; // product id
$cart_total = 199.99;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] === $product_id ) {
$in_cart = true;
$key = $cart_item_key;
break;
}
}
if( WC()->cart->total < $cart_total ) {
if ( $in_cart ) WC()->cart->remove_cart_item( $key );
}
}
You should not use template_redirect hook to add or remove a free product based on a cart total threshold amount… Also your code is a bit outdated with some mistakes.
Instead use woocommerce_before_calculate_totals hook that is Ajax enabled, this way:
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users (and avoiding the hook repetition)
if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 200; // The threshold amount for cart total
$free_product_id = 339; // ID of the free product
$cart_items_total = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( $cart_item['data']->get_id() == $free_product_id ) {
$free_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If Cart total is up to the defined amount and if the free products is not in cart, we add it.
if ( $cart_items_total >= $threshold_amount && ! isset($free_item_key) ) {
$cart->add_to_cart( $free_product_id );
}
// If cart total is below the defined amount and free product is in cart, we remove it.
elseif ( $cart_items_total < $threshold_amount && isset($free_item_key) ) {
$cart->remove_cart_item( $free_item_key );
}
}
Code goes on functions.php file of your active child theme (or active theme). Tested and works.
Related: Other similar answer threads