More and more online stores are helping to fulfil their Corporate Social Responsibility by asking their customers to add on a charitable donation based on their cart total. That’s exactly what our client The Barn Little London asked us to include when we built their online store. With The Barn, a donation totalling 10% of the customers cart is collected on behalf of the UK Harvest charity.
The Barn wanted to make this a requirement of shopping with them, so we added a function to hook into the WooCommerce cart, return the cart total, and add on the donation, displaying this to the customer in the checkout totals table.
WooCommerce Percentage based Donation
This function calculates the donation or surcharge total based on a percentage of the cart total. In the example below we’re adding a 10% donation, but you can change this to be the percentage that you need, just update the $percentage
variable. Percentage values are from 0 to 1. 0 being 0% and 1 being 100%. So a 5% donation for instance would look like this $percentage = 0.05
/**
* Add a 10% donation to the cart / checkout
* change the $percentage to set the donation to a value to suit
**/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_donation' );
function woocommerce_custom_donation() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 0.10; // 10%
// uncomment the line below to include shipping fees in the donation/surcharge calculation
// $donation = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$donation = $woocommerce->cart->cart_contents_total * $percentage;
$woocommerce->cart->add_fee( 'Donation to UK Harvest Charity', $donation, true, '' );
}
WooCommerce fixed Donation
The above function could be easily modified so that a set donation or surcharge value is applied, rather than being a percentage based calculation.
In the example below, we’re applying a £5 donation to the customer’s order.
/**
* Add a £5 donation to the cart / checkout
* change the $value variable to set the donation to a value that suits
*/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_donation_fixed' );
function woocommerce_custom_donation_fixed() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$value = 5;
$donation = $woocommerce->cart->cart_contents_total + $value;
$woocommerce->cart->add_fee( 'Donation to UK Harvest Charity', $donation, true, '' );
}
Where should I add this code?
The above snippets should be added to your theme’s functions.php
file.