Do you have some product which is costly to ship and want to charge extra for it? But you don’t want to create separate shipping method but instead use your existing one?
In this tutorial we will go over how you can add extra price to shipping rates depending on the products in the cart. There are a couple of important things we need to achieve:
- Add extra price to existing shipping method and not create a new shipping method
- Calculate taxes automatically and correctly
WooCommerce has two possible hooks for modifying shipping rates:
- woocommerce_package_rates
- woocommerce_shipping_method_add_rate_args
More common of the two is woocommerce_package_rates. However, it has problem related to tax calculation. The hook is run after taxes have been calculated and you need to calculate them manually if you use it.
Alternative is woocommerce_shipping_method_add_rate_args. It’s run when WooCommerce fetches available shipping rates and taxes are calculated after that. By modifying shipping rates before taxes are calculated they get automatically calculated correctly.
Here is example code how you can charge $ 3 extra for a product named “Bananas” and shipping method called “Economy Shipping”. Feel free to edit the product and the shipping method to suit your needs. The code can be added with Code Snippets or to your theme’s functions.php file.
<?php
/**
* Add extra price to shipping for a product
*/
add_filter( 'woocommerce_shipping_method_add_rate_args', 'snippet_charge_shipping_extra_per_product', 100, 2 );
function snippet_charge_shipping_extra_per_product( $args, $shipping_method ) {
// Check that cart contains a product named "Bananas"
$contains = false;
foreach ( WC()->cart->get_cart() as $key => $item ) {
if ( isset( $item['data'] ) && method_exists( $item['data'], 'get_title' ) && $item['data']->get_title() === "Bananas" ) {
$contains = true;
break;
}
}
// Check that we are processing Economy Shipping method
if ( $contains && $shipping_method && $shipping_method->get_title() === "Economy Shipping" ) {
// Add extra of $ 3 to the shipping method. Extra price is added to $args['cost']
// Taxes will be calculated from the new price.
$args['cost'] += 3;
}
return $args;
}
That’s all. When you have “Bananas” in the cart, Economy Shipping will be $ 3 more than the default price.
Want to do this without code?
WooCommerce Conditional Shipping Pro allows you to add extra shipping charges without any code. You can use many different conditions such as categories, products and shipping classes. The plugin has easy user interface for defining conditions and extra charges for shipping.