Progressive percent discount based on cart amount - php

I am trying to make a simple discount code for WooCommerce that gives you a percent discount before buying. Lets say that if you add products worth $100 you get 2% discount and if you add products worth $250 you get 4%, etc.
The only thing I found was this:
// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
/**
* Add custom fee if more than three article
* #param WC_Cart $cart
*/
function add_custom_fees( WC_Cart $cart ){
if( $cart->cart_contents_count < 3 ){
return;
}
// Calculate the amount to reduce
$discount = $cart->subtotal * 0.1;
$cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}
But could not manage to make it work with the modifying the hooks with those for the price.
How can I achieve this?

Here is the way to do it using conditions based on cart subtotal excl tax amount to add this progressive percentage as a negative fee, so a discount:
add_action( 'woocommerce_cart_calculate_fees','cart_price_progressive_discount' );
function cart_price_progressive_discount() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$has_discount = false;
$stotal_ext = WC()->cart->subtotal_ex_tax;
// Discount percent based on cart amount conditions
if( $stotal_ext >= 100 && $stotal_ext < 250 ) {
$percent = -0.02;
$percent_text = ' 2%';
$has_discount =true;
} elseif( $stotal_ext >= 250 ) {
$percent = -0.04;
$percent_text = ' 4%';
$has_discount =true;
}
// Calculation
$discount = $stotal_ext * $percent;
// Displayed text
$discount_text = __('Discount', 'woocommerce') . $percent_text;
if( $has_discount ) {
WC()->cart->add_fee( $discount_text, $discount, false );
}
// Last argument in add fee method enable tax on calculation if "true"
}
This goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.
Similar: WooCommerce - Conditional Progressive Discount based on number of items in cart
Reference: WooCommerce class - WC_Cart - add_fee() method

Related

WooCommerce: Double discount on sale products with coupon

I want to double the discount for products on sale with a coupon code.
For example: The product is on sale with a 10% discount. If I add the coupon code doublediscount I want to double that discount to 20%.
The coupon discount should have limit of 15%.
So if a product is on sale with a 30% discount, the max added discount with the coupon code should be 15%. Resulting in a 45% discount on the regular price (sale + extra discount).
My code so far is this:
add_action( 'woocommerce_before_calculate_totals', 'double_saleprice_coupon' );
function double_saleprice_coupon( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
global $woocommerce;
$coupon_id = 'doublediscount';
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if product in cart is on sale
$product = $cart_item['data'];
$cart_item_regular_price = $cart_item['data']->get_regular_price();
$cart_item_sale_price = $cart_item['data']->get_sale_price();
$cart_item_diff = $cart_item_regular_price - $cart_item_sale_price;
$cart_item_per_cent = round( $cart_item_diff / $cart_item_regular_price * 100, 0 );
if ( $product->is_on_sale() && wc_pb_is_bundled_cart_item($cart_item) === false && $cart_item_per_cent < 15 ) {
echo 'on sale';
echo $cart_item_per_cent;
}
}
}
I loop through all cart items and check if they are on sale and if the discount is below 15%. If that's the case, I want to change the discount for these cart items.
If the cart item has a discount above 15% I don't want to do anything. So the coupon code doublediscount would apply 15% to them.
I just don't know how to add/change the discount of a cart item.
You can use the woocommerce_coupon_get_discount_amount hook instead in combination with the following coupon settings:
Set correctly your coupon code: doublediscount
Discount type: Percentage
Amount: 15
Steps applied in this answer:
Only if the specific coupon code matches and the product is on sale
If a product is not on sale, no discount will be applied (by the else condition equal to 0. However, if this doesn't apply, you can simply remove the else condition)
Current percentage discount of the on sale product is calculated.
If this is less than the maximum added discount (15),
then the discount is doubled
If this is more, the maximum discount added (15) will be applied automatically
So you get:
function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {
// Returns true when viewing the cart page & only apply for this coupon
if ( is_cart() || is_checkout() && $coupon->get_code() == 'doublediscount' ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// On sale
if ( $product->is_on_sale() ) {
// Regular price
$cart_item_regular_price = $product->get_regular_price();
// Sale price
$cart_item_sale_price = $product->get_sale_price();
// Calculate the percentage difference
$cart_item_diff = $cart_item_regular_price - $cart_item_sale_price;
$cart_item_percentage = round( $cart_item_diff / $cart_item_regular_price * 100, 0 );
// Get maximum added discount
$max_added_discount = $coupon->get_amount();
// Less than maximum added discount
if ( $cart_item_percentage < $max_added_discount ) {
$discount = round( ( $price_to_discount * $cart_item_percentage ) / 100, 0 );
}
} else {
$discount = 0;
}
}
}
return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );

Woocommerce custom shipping rate calculation based on weight

In Woocommerce, I would like to have a function that I can include within my theme that adds shipping rate based on price and weight.
if price is above 20USD shipping is free, below Shipping cost : 3USD
if weight is above 10kg shipping fee is 2USD extra
Based on "Shipping calculated on the items weight and cart amount" answer thread, I tried something like the beneath code:
//Adding a custom Shipping Fee to cart based conditionally on weight and cart amount
add_action('woocommerce_cart_calculate_fees', 'custom_conditional_shipping_fee', 10, 1);
function custom_conditional_shipping_fee( $cart_object ){
#### SETTINGS ####
// Your targeted "heavy" product weight
$target_weight = 1;
// Your targeted cart amount
$target_cart_amount = 20;
// Price by Kg;
$price_kg = 2;
// Amount set in 'flat rate' shipping method;
$flat_rate_price;
// Initializing variables
$fee = 0;
$calculated_weight = 0;
// For cart SUBTOTAL amount EXCLUDING TAXES
WC()->cart->subtotal_ex_tax >= $target_cart_amount ? $passed = true : $passed = false ;
// For cart SUBTOTAL amount INCLUDING TAXES (replace by this):
// WC()->cart->subtotal >= $target_cart_amount ? $passed = true : $passed = false ;
// Iterating through each cart items
foreach( $cart_object->get_cart() as $cart_item ){
// Item id ($product ID or variation ID)
if( $cart_item['variation_id'] > 0)
$item_id = $cart_item['variation_id'];
else
$item_id = $cart_item['product_id'];
// Getting the product weight
$product_weight = get_post_meta( $item_id , '_weight', true);
// Line item weight
$line_item_weight = $cart_item['quantity'] * $product_weight;
// When cart amount is up to 1kg, Adding weight of heavy items
if($passed && $product_weight < $target_weight)
$calculated_weight += $line_item_weight;
}
#### Making the fee calculation ####
// Cart is up to 250 with heavy items
if ( $passed && $calculated_weight != 0 ) {
// Fee is based on cumulated weight of heavy items
$fee = ($calculated_weight * $price_kg) - $flat_rate_price;
}
// Cart is below 250
elseif ( !$passed ) {
// Fee is based on cart total weight
$fee = ($cart_object->get_cart_contents_weight( ) * $price_kg) - $flat_rate_price;
}
#### APPLYING THE CALCULATED FEE ####
// When cart is below 250 or when there is heavy items
if ($fee > 0){
// Rounding the fee
$fee = round($fee);
// This shipping fee is taxable (You can have it not taxable changing last argument to false)
$cart_object->add_fee( __('Shipping weight fee', 'woocommerce'), $fee, true);
}
}
Edit:
And at the same time I want it to show this immediately on the cart page. Now it is showing "enter address to view shipping options". Basically just look at total of cart and show either a rate or free shipping based on the rules described for weight and price.
woocommerce_package_rates is the right filter to customize the shipping rate.
You can achieve this by following way.
Step-1: Create two shipping method, Free shipping and Flat rate with coast 3$
Step-2: Copy and paste below code snippet into functions.php
Config the flat rate and free shipping properly on the snippet.
add_filter( 'woocommerce_package_rates', 'modify_shipping_rate', 15, 2 );
function modify_shipping_rate( $available_shipping_methods, $package ){
global $woocmmerce;
$total_weight = WC()->cart->cart_contents_weight;
$total_coast = WC()->cart->get_cart_contents_total();
if( $total_coast >= 20 ){
unset($available_shipping_methods['flat_rate:1']); //Remove flat rate for coat abobe 20$
}elseif( $total_weight > 10 ){
unset($available_shipping_methods['free_shipping:1']); // remove free shipping for below 20$
$available_shipping_methods['flat_rate:1']->cost += 2; // add 2$ if weight exceeds 10KG
}else{
unset($available_shipping_methods['free_shipping:1']); // remove free shipping for below 20$
}
return $available_shipping_methods;
}
Use below snippet to change the default cart message.
add_filter( 'woocommerce_cart_no_shipping_available_html', 'change_msg_no_available_shipping_methods', 10, 1 );
add_filter( 'woocommerce_no_shipping_available_html', 'change_msg_no_available_shipping_methods', 10, 1 );
function change_msg_no_available_shipping_methods( $default_msg ) {
$custom_msg = "Enter address to view shipping options";
if( empty( $custom_msg ) ) {
return $default_msg;
}
return $custom_msg;
}
The following code isn't based on a custom fee, but on shipping methods customizations.It requires to set in shipping settings, for each shipping zone:
A "Flat Rate" with a defined cost ($3 for you)
A "Free Shipping" with no requirements (no restrictions).
The code will handle flat rate calculation cost based on the weight and also the tax calculations.
The code will work for any shipping zone without needing to define in the code the shipping method IDs.
Here is the code:
add_filter( 'woocommerce_package_rates', 'filter_package_rates_callback', 10, 2 );
function filter_package_rates_callback( $rates, $package ) {
## -------- Settings -------- ##
$targeted_total = 20; // The targeted cart amount
$weight_threshold = 10; // The cart weight threshold
$extra_for_10kg = 2; // 10 Kg addition extra cost;
$total_weight = WC()->cart->get_cart_contents_weight();
$cart_subtotal = WC()->cart->get_subtotal(); // Excluding taxes
// Set shipping costs based on weight
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
if( $cart_subtotal < $targeted_total || $total_weight >= $weight_threshold ){
// Remove Free shipping Method
if( 'free_shipping' === $rate->method_id ) {
unset( $rates[$rate_key] );
}
// Flat rate calculation cost when 10 kg weight is reached
if( 'flat_rate' === $rate->method_id && $total_weight >= $weight_threshold ) {
// The default rate cost (set in the shipping method)
$default_cost = $rate->cost;
// The new calculated cost (up to 10 kg)
$new_cost = $default_cost + $extra_for_10kg;
// Tax rate conversion (for tax calculations)
$tax_rate_converion = $new_cost / $default_cost;
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// TAXES RATE COST (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){
// New tax calculated cost
$taxes[$key] = $tax * $tax_rate_converion;
$has_taxes = true;
}
}
// Set new taxes cost
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
} else {
// Remove Flat Rate methods (keeping Free Shipping Method only)
if( 'flat_rate' === $rate->method_id ) {
unset( $rates[$rate_key] );
}
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Refresh the shipping caches: (required)
1) This code is already saved on your function.php file.
2) In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.
Displaying shipping methods directly (Regarding your question edit)
The provided information in your question is not enough to see how this can be managed.
If you are selling in one country, and you have a unique shipping zone, you can force the country for unlogged customers to get the shipping methods displayed, using the following:
add_action( 'template_redirect', 'allow_display_shipping_methods' );
function allow_display_shipping_methods() {
// HERE define the targeted country code
$country_code = 'GB';
// Set the shipping country if it doesn't exist
if( ! WC()->customer->get_shipping_country() )
WC()->customer->set_shipping_country('GB');
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Now this is another question, in your initial question and should be asked as a new question.
Related answers:
Set a custom shipping rate cost calculated on cart total weight in WooCommerce
Free shipping depending on weight and on minimal cart amount
Shipping cost based on cart total weight in Woocommerce 3
Hide and unhide a specific shipping methods based on shipping class in WooCommerce

Add custom fee based on total weight in Woocommerce

In WooCommerce, I am trying to add a an additional shipping fee based on cart weight.
For the first 1500g the fee is 50$.
Above 1500g we add 10$ to this initial $50 by steps of 1000g
So for example:
if cart weight is 700g we add a fee of $50,
if cart weight is 2600g we add a fee of $70 ($50 + $10 +$10) …
I am stuck on the calculation:
function weight_add_cart_fee() {
$feeaddtocart = get_option('feeaddtocart');
$customweight = get_option('customweight');
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_weight = WC()->cart->get_cart_contents_weight();
if ($cart_weight <= 500 ) {
$get_cart_total = $woocommerce->cart->get_cart_total();
$newtotal = $get_cart_total + 50;
WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $newtotal, false );
}
}
How can I achieve this? Any help is appreciated.
It can be done very easily with a custom function hooked in woocommerce_cart_calculate_fees action hook…
Updated:
Added conversion of cart weight in grams (instead of kilos by default)
Now for the first 1500g the fee is 50$ (instead of 500g)
Now above 1500g it add $10 by steps of 1000g.
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Convert cart weight in grams
$cart_weight = $cart->get_cart_contents_weight() * 1000;
$fee = 50; // Starting Fee below 500g
// Above 500g we add $10 to the initial fee by steps of 1000g
if( $cart_weight > 1500 ){
for( $i = 1500; $i < $cart_weight; $i += 1000 ){
$fee += 10;
}
}
// Setting the calculated fee based on weight
$cart->add_fee( __( 'Weight shipping fee' ), $fee, false );
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.

Cart discount based on cart item count and only for items that are not in sale

In WooCommerce, I would like to give a discount of 10% specifically for those products that are not on sale. If cart item count is 5 or more items and not on sale, then I give a discount of 10%.
I use the following code to get a discount based on cart item count restriction here:
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
/**
* Add custom fee if more than three article
* #param WC_Cart $cart
*/
function add_custom_fees( WC_Cart $cart ){
if( $cart->cart_contents_count < 5 ){
return;
}
// Calculate the amount to reduce
$discount = $cart->subtotal * 0.1;
$cart->add_fee( '10% discount', -$discount);
}
But I don't know how to apply the discount only for items that are not in sale. How can I achieve it?
Thanks.
Here is a custom hooked function that will apply to cart a discount, if there is 5 or more items in cart and no products on sale:
add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only when there is 5 or more items in cart
if( $cart->get_cart_contents_count() >= 5):
// Initialising variable
$is_on_sale = false;
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
// Getting an instance of the product object
$product = $cart_item['data'];
// If a cart item is on sale, $is_on_sale is true and we stop the loop
if($product->is_on_sale()){
$is_on_sale = true;
break;
}
}
## Discount calculation ##
$discount = $cart->subtotal * -0.1;
## Applied discount (no products on sale) ##
if(!$is_on_sale )
$cart->add_fee( '10% discount', $discount);
endif;
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works perfectly.

Cart discount for a product category based on quantity calculations

I wan to add a function to woocommerce that will calculate a 10% discount when 12-23 items from one category is added to the cart.
Then if 24 - 47 items of the category are added it would be a 15% discount.
Last if 48+ items from this category are added it would be a 20% discount.
actual code example would be awesome as I am new to woocommerce
Updated — Corrected code mistakes and added enhancements in the outputted discount text
Here is the function hooked in woocommerce_cart_calculate_fees hook that is going to make the discount for that particular category (or subcategory too) based on cart item quantity calculations.
This is the code:
add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_wine_discount', 10, 1 );
function cart_items_quantity_wine_discount($cart_object) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your category (can be an ID, a slug or the name)
$category = 34; // or a slug: $category = 'wine';
$category_count = 0;
$category_total = 0;
$discount = 0;
// Iterating through each cart item
foreach($cart_object->get_cart() as $cart_item):
if( has_term( $category, 'product_cat', $cart_item['product_id']) ):
$category_count += $cart_item['quantity'];
$category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price)
endif;
endforeach;
$discount_text = __( 'Quantity discount of ', 'woocommerce' );
// ## CALCULATIONS ##
if ( $category_count >= 12 && $category_count < 24 ) {
$discount -= $category_total * 0.1; // Discount of 10%
$discount_text_output = $discount_text . '10%';
} elseif ( $category_count >= 24 && $category_count < 48 ) {
$discount -= $category_total * 0.15; // Discount of 15%
$discount_text_output = $discount_text . '15%';
} elseif ( $category_count >= 48 ) {
$discount -= $category_total * 0.2; // Discount of 20%
$discount_text_output = $discount_text . '20%';
}
// Adding the discount
if ( $discount != 0 && $category_count >= 12 )
$cart_object->add_fee( $discount_text_output, $discount, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
Note: Last argument in add_fee() method is related to applying the tax or not to the discount…
Code is tested and fully functional.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Other similar: Discount for Certain Category Based on Total Number of Products

Categories