add_action( 'woocommerce_order_before_calculate_totals', "custom_order_before_calculate_totals", 10, 3);
function custom_order_before_calculate_totals($and_taxes, $order ) {
// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
// loop all products and calculate total deposit
$total_deposit = 0;
foreach( $order->get_items() as $item_id => $item ) {
// get the WC_Product object
$product = $item->get_product();
// get the quantity
$product_quantity = $item->get_quantity();
// get the deposit amount
$deposit = $product->get_attribute('deposit') * $product_quantity;
// sum of deposits from all products
$total_deposit += $deposit;
}
// update the Deposit fee if it exists
$deposit_fee_exists = false;
foreach( $order->get_fees() as $item_id => $item_fee ) {
$fee_name = $item_fee->get_name();
if ( $fee_name == 'Deposit' ) {
$item_fee->set_tax_status('none'); // no tax on deposit
$item_fee->set_total($total_deposit);
$deposit_fee_exists = true;
break;
}
}
// if there isn't an existing deposit fee then add it
if ( $total_deposit > 0 && !$deposit_fee_exists ) {
// Get a new instance of the WC_Order_Item_Fee Object
$item_fee = new WC_Order_Item_Fee();
$item_fee->set_name( "Deposit" ); // Generic fee name
$item_fee->set_amount( $total_deposit ); // Fee amount
$item_fee->set_tax_status( 'none' ); // or 'none'
$item_fee->set_total( $total_deposit ); // Fee amount
// Add Fee item to the order
$order->add_item( $item_fee );
}
}