Updated: Added WooCommerce 3+ compatibility
This is possible and easy with the add_fee()
method in the woocommerce_cart_calculate_fees
hook. Here is a simple usage example for simple products, with 2 categories and based on the product dimensions measurement calculations for each item of the cart. Its also possible for other product types.
Here is the example code (That you will need to customize for your own case):
add_action( 'woocommerce_cart_calculate_fees','custom_applied_fee', 10, 1 );
function custom_applied_fee( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be an ID, a slug or the name… or an array of this)
$category1 = 'plain';
$category2 = 'plywood';
// variables initialisation
$fee = 0;
$coef = 1;
// Iterating through each cart item
foreach( $cart_object->get_cart() as $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
$product = $cart_item['data']; // Get the product object
// Get the dimentions of the product
$height = $product->get_height();
$width = $product->get_width();
// $length = $product->get_length();
// Initialising variables (in the loop)
$cat1 = false; $cat2 = false;
// Detecting the product category and defining the category coeficient to change price (for example)
// Set here for each category the modification calculation rules…
if( has_term( $category1, 'product_cat', $cart_item['product_id']) )
$coef = 1.15;
if( has_term( $category2, 'product_cat', $cart_item['product_id']) )
$coef = 1.3;
// ## CALCULATIONS ## (Make here your conditional calculations)
$dimention = $height * $with;
if($dimention <= 10){
$fee += 10 * $coef;
} elseif($dimention > 10 && $dimention <= 20){
$fee += 20 * $coef;
} elseif($dimention > 20){
$fee += 30 * $coef;
}
}
// Set here the displayed fee text
$fee_text = __( 'Packaging fee', 'woocommerce' );
// Adding the fee
if ( $fee > 0 )
WC()->cart->add_fee( $fee_text, $fee, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
You will have to set your own categories with the related changes calculations for each category. You will get a non detailed general output fee calculated taking into account each item in the cart.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
The code is tested and fully functional.
Related Answers: