In Woocommerce, I am trying to auto remove a gift product from cart if cart item is less than 300,000 dongs.
Here is my code:
add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
// Run only in the Cart or Checkout Page
global $woocommerce;
$current = WC()->cart->cart_contents_total;
$min_amount= 300000;
$prod_to_remove = 357;
if ( $current < $min_amount) {
if( is_cart() || is_checkout() ) {
// Cycle through each product in the cart
foreach( WC()->cart->cart_contents as $prod_in_cart ) {
// Get the Variation or Product ID
$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
// Check to see if IDs match
if( $prod_to_remove == $prod_id ) {
// Get it's unique ID within the Cart
$prod_unique_id = WC()->cart->generate_cart_id( $prod_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
wc_add_notice( __( 'Quà tặng của bạn đã bị xóa khỏi giỏ hàng vì ' ), 'notice' );
}
}
}
}}
But the problem is that it does not work with product variations.
Any help is appreciated.
Uptaded (to handle multiple items to be removed).
Try the following revisited code, that will work with product variations too in a better way:
add_action( 'woocommerce_check_cart_items', 'conditionally_remove_specific_cart_item' );
function conditionally_remove_specific_cart_item() {
## -- Settings -- ##
$min_required = 300000; // The minimal required cart subtotal
$items_to_remove = array( 446, 27 ); // Product Ids to be removed from cart
// Only if cart subtotal is less than 300000
if( WC()->cart->cart_contents_total >= $min_required )
return;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if( array_intersect( $items_to_remove, array( $cart_item['variation_id'], $cart_item['product_id'] ) ) ) {
// Remove cart item
WC()->cart->remove_cart_item( $cart_item_key );
// Add a custom notice
wc_add_notice( sprintf(
__( "Your gift has been removed from the cart because its requires a minimal cart amount of %s", "woocommerce" ),
$min_required ), 'notice' );
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
In cart page:
In checkout page:
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
The code below auto add a product to cart in WooCommerce:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64;
$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() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
The answer Checking if customer has already bought something in WooCommerce allows to check if user has already make a purchase or not with a custom conditional function has_bought().
So what I would like is to check if the customer has ordered before and:
If it's their first order, force product A into the cart OR
If they've already made one or more purchases, force product B into
the cart
But I didn't find the way to use it in my code.
Any help will be appreciated.
The code below uses the custom function has_bought(). It auto add to cart a different product for new customers and confirmed customers:
add_action( 'template_redirect', 'add_product_to_cart_conditionally' );
function add_product_to_cart_conditionally() {
if ( is_admin() ) return; // Exit
// Below define the product Id to be added:
$product_A = 37; // <== For new customers that have not purchased a product before (and guests)
$product_B = 53; // <== For confirmed customers that have purchased a product before
$product_id = has_bought() ? $product_B : $product_A;
// If cart is empty
if( WC()->cart->is_empty() ) {
WC()->cart->add_to_cart( $product_id ); // Add the product
}
// If cart is not empty
else {
// Loop through cart items (check cart items)
foreach ( WC()->cart->get_cart() as $item ) {
// Check if the product is already in cart
if ( $item['product_id'] == $product_id ) {
return; // Exit if the product is in cart
}
}
// The product is not in cart: We add it
WC()->cart->add_to_cart( $product_id );
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: Checking if customer has already bought something in WooCommerce
So by using the docs on the WooCommerce site I've been able to add a new product to the basket automatically which works great.
I calculate the number of products by taking the current quantity in the cart and multiplying it by a percentage modifier, this also works.
My problem comes when I update the cart with a new quantity as the bonus product quantity doesn't get updated.
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 265;
$found = false;
// Get the current cart quantity
foreach ( WC()->cart->get_cart() as $cart_item ) {
$quantity = $cart_item['quantity'];
$percentage = .25;
$bonus = $quantity * $percentage;
}
//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->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id, $bonus );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id, $bonus );
}
}
}
Does anyone have an idea on how to get this to automatically recalculate when update cart is clicked?
Preliminary remarks:
Your code doesn't work when cart is empty as $bonus variable is not defined and you get an error…
Also as you are setting a variable float number for quantity: So if the quantity is not an integer, customer can't change and update the cart items quantities.
This is kind of complex, your bonus quantity need to be updated in another hooked function when:
A product is added to cart
Customer update quantities in cart page
Customer remove items from cart
Also, there is small errors like $_product->id that should instead $_product->get_id() in WC 3+
So your revisited code with additional hooked functions will be:
add_action( 'template_redirect', 'auto_add_product_to_cart', 50 );
function auto_add_product_to_cart() {
if ( ! is_admin() ) {
$cart = WC()->cart; // <== Cart object
$product_id = 37; // <== Specific product to be auto added
$bonus_rate = .25; // <== Bonus rate
$found = false;
// Check if product already in cart
if ( ! $cart->is_empty() ) {
$contents_count = $cart->get_cart_contents_count(); // The cart items count
$bonus_qty = $contents_count * $bonus_rate; // Bonus quantity calculation
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == $product_id ){
$found = true;
break; // Stop the loop
}
}
// Product is not found in the loop, we add it
if( ! $found )
$cart->add_to_cart( $product_id, $bonus_qty );
} else {
// There is no items in cart, we add it
$cart->add_to_cart( $product_id, $bonus_rate );
}
}
}
// Calculate, set and update bonus quantity
add_action( 'woocommerce_before_calculate_totals', 'conditional_bonus_quantity_calculation', 20, 1 );
function conditional_bonus_quantity_calculation( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$bonus_rate = .25; // <== Bonus rate
$product_id = 37; // <== Specific product to be auto added
$contents_count = $cart->get_cart_contents_count(); // Total cart items count
// Loop through cart items to check our specific product
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// If specific product is in cart
if ( $cart_item['data']->get_id() == $product_id ){
$calc_qty = $cart_item['quantity'] < 1 ? 1 : $cart_item['quantity'];
// Bonus quantity calculation
if( $contents_count > 1 )
$bonus_qty = round( $contents_count - $calc_qty ) * $bonus_rate;
else
$bonus_qty = $bonus_rate;
// Update item quantity
$cart->set_quantity( $cart_item_key, $bonus_qty, false );
}
}
}
// Allowing float numbers quantity (step by .25) for a specific product
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 20, 2 );
function custom_quantity_input_args( $args, $product ) {
// Only for your specific product ID on cart page
if( $product->get_id() != 37 && is_cart() ) return $args;
//$args['input_value'] = 0.25; // Default starting value (Optional)
$args['min_value'] = 0.25;
$args['step'] = 0.25;
$args['pattern'] = '[0-9.]*';
$args['inputmode'] = 'numeric';
return $args;
}
// Allowing float numbers in Stock management
remove_filter('woocommerce_stock_amount', 'intval');
add_filter('woocommerce_stock_amount', 'floatval');
Code goes in function.php file of the active child theme (or active theme).
Tested and works.
I am trying to automatically apply coupons in my WooCommerce store based on product ID and quantity conditions. My end goal is for a particular coupon to apply automatically when TWO (2) of the desired products are added to the cart, and for another coupon to app,y automatically whenever THREE (3) of the desired products are added to the cart. A single quantity of the product should have no discount. The following is the CORRECTED version of the code, which now works:
add_action( 'woocommerce_before_cart', 'conditional_auto_add_coupons' );
function conditional_auto_add_coupons() {
if ( !WC()->cart->is_empty() ){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 103;
$coupon1 = 'soccer-sibling-2';
$coupon2 = 'soccer-sibling-3';
// First cart loop: Counting number of subactegory items in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $target_pid == $cart_item['data']->id ){
// Removes any coupons in the cart already
WC()->cart->remove_coupons();
if( 2 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon1 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon1 );
wc_add_notice( __( 'The multiple sibling discount has been applied.', 'theme_domain' ), 'success' );
} elseif( 3 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon2 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon2 );
wc_add_notice( __( 'The multiple sibling discount has been applied.', 'theme_domain' ), 'success' );
}
// Recalculates Cart Totals to show correct price
WC()->cart->calculate_totals();
}
}
}
}
Theres is a lot of errors in your code and it's a little obsolete too...
I have rewrite everithing in your function and hooked it in another hook.
Here is your revisited code:
add_action( 'woocommerce_before_cart', 'conditional_auto_add_coupons' );
function conditional_auto_add_coupons() {
if ( !WC()->cart->is_empty() ){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 103;
$coupon1 = 'soccer-sibling-2';
$coupon2 = 'soccer-sibling-3';
// First cart loop: Counting number of subactegory items in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $target_pid == $cart_item['data']->id ){
if( 2 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon1 ) ){
WC()->cart->add_discount( $coupon1 );
wc_add_notice( __( 'A quantity discount of <strong>5%</strong> has been added.', 'theme_domain' ), 'success' );
} elseif( 3 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon2 ) ){
WC()->cart->add_discount( $coupon2 );
wc_add_notice( __( 'A quantity discount of <strong>10%</strong> has been added.', 'theme_domain' ), 'success' );
}
}
}
}
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This should work and will not make your website crash, but I haven't really test it, as this is very particular.
Coming back here a few years later: I found a loophole that caused an issue. Because the function was counting the total cart contents, rather than just the quantity of the product the coupon is applied to, customers could exploit this to add non-coupon related products to get the additional coupons for the discounted product. The following code closes the loophole by checking the quantity of just the product in question:
add_action( 'woocommerce_before_cart', 'conditional_auto_add_coupons_tourney' );
function conditional_auto_add_coupons_tourney() {
if ( !WC()->cart->is_empty() ){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 96;
$coupon1 = 'multiple-25';
$coupon2 = 'multiple-50';
// UPDATE: switched WC()->cart->get_cart_contents_count() for $quantity on 236 and 240
// First cart loop: Counting number of subcategory items in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $target_pid == $cart_item['product_id'] ){
WC()->cart->remove_coupons();
$quantity = $cart_item['quantity']; // Added to find quantity of specific product
if( 5 <= $quantity && !WC()->cart->has_discount( $coupon2 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon2 );
wc_add_notice( __( 'The multiple team discount has been applied.', 'theme_domain' ), 'success' );
} elseif( 2 <= $quantity && !WC()->cart->has_discount( $coupon1 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon1 );
wc_add_notice( __( 'The multiple team discount has been applied.', 'theme_domain' ), 'success' );
}
WC()->cart->calculate_totals();
}
}
}
}
I am looking for the right hook in WooCommerce because I need to add a promotional product to the cart when a certain cart amount of is reached, such as 100 conventional units.
I have also used the hook 'init' but I do not think it's right.
Here is my code:
function add_free_product_to_cart(){
global $woocommerce;
$product_id = 2006;
$found = false;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 )
{
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values )
{
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
if(!$found)
{
$maximum = 100;
$current = WC()->cart->subtotal;
if($current > $maximum){
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
add_action( 'woocommerce_add_to_cart', 'add_free_product_to_cart' );
which hook I should use for that purpose?
Or could you give me a related link to to some similar problem?
Thanks
As you are targeting a certain cart amount to add a promotional product in the cart, you could use woocommerce_before_calculate_totals hook to achieve this with a custom built function.
You have also to remove that promo item if customer update the cart (which is embed in that custom function too).
Here is the code:
add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 );
function adding_promotional_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$promo_id = 99; // <=== <=== <=== Set HERE the ID of your promotional product
$targeted_cart_subtotal = 100; // <=== Set HERE the target cart subtotal
$has_promo = false;
$subtotal = 0;
if ( ! $cart->is_empty() ){
// Iterating through each item in cart
foreach ($cart->get_cart() as $item_key => $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
// If Promo product is in cart
if( $product_id == $promo_id ) {
$has_promo = true;
$promo_key= $item_key;
} else {
// Adding subtotal item to global subtotal
$subtotal += $cart_item['line_subtotal'];
}
}
// If Promo product is NOT in cart and target subtotal reached, we add it.
if( ! $has_promo && $subtotal >= $targeted_cart_subtotal ) {
$cart->add_to_cart( $promo_id );
// echo 'add';
// If Promo product is in cart and target subtotal is not reached, we remove it.
} elseif( $has_promo && $subtotal < $targeted_cart_subtotal ) {
$cart->remove_cart_item( $promo_key );
}
}
}
This code goes on function.php file of your active child theme (or theme) or in any plugin file.
This code its tested and works.
Related thread: WooCommerce - Auto add or auto remove a freebie product from cart
Code updated on (2018-10-01)