Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bolderelements/46b29acfd5bd3dc24e970c4deea43f99 to your computer and use it in GitHub Desktop.
Save bolderelements/46b29acfd5bd3dc24e970c4deea43f99 to your computer and use it in GitHub Desktop.
Discount shipping cost based on number of items being purchased
/**
* Discount shipping cost based on number of items being purchased
* Further narrowed down to only run on BE Table Rate options
* Code snippets should be added to the functions.php file of your child theme
*
* @return array
*/
add_filter( 'woocommerce_package_rates', 'add_shipping_percentage_discount', 10, 2 );
function add_shipping_percentage_discount( $rates, $package ) {
// get number of items
$item_quantity = WC()->cart->get_cart_contents_count();
// only run if multiple items ordered
if( $item_quantity > 1 ) {
foreach( $rates as $key => $value ) {
if( $value->method_id == 'betrs_shipping' ) {
if( $item_quantity == 2 ) {
// calculate 20% discount
$discount = $value->get_cost() * .20;
} elseif( $item_quantity >= 3 ) {
// calculate 25% discount
$discount = $value->get_cost() * .25;
}
// subtract discount
$rates[ $key ]->set_cost( $value->get_cost() - $discount );
}
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment