WC_Cart::add_fee PHP Method

add_fee() public method

Add additional fee to the cart.
public add_fee ( string $name, float $amount, boolean $taxable = false, string $tax_class = '' )
$name string Unique name for the fee. Multiple fees of the same name cannot be added.
$amount float Fee amount.
$taxable boolean (default: false) Is the fee taxable?
$tax_class string (default: '') The tax class for the fee if taxable. A blank string is standard tax class.
    public function add_fee($name, $amount, $taxable = false, $tax_class = '')
    {
        $new_fee_id = sanitize_title($name);
        // Only add each fee once
        foreach ($this->fees as $fee) {
            if ($fee->id == $new_fee_id) {
                return;
            }
        }
        $new_fee = new stdClass();
        $new_fee->id = $new_fee_id;
        $new_fee->name = esc_attr($name);
        $new_fee->amount = (double) esc_attr($amount);
        $new_fee->tax_class = $tax_class;
        $new_fee->taxable = $taxable ? true : false;
        $new_fee->tax = 0;
        $new_fee->tax_data = array();
        $this->fees[] = $new_fee;
    }

Usage Example

 /**
  * Add order/subscription fee line items to the cart when a renewal order, initial order or resubscribe is in the cart.
  *
  * @param WC_Cart $cart
  * @since 2.0.13
  */
 public function maybe_add_fees($cart)
 {
     if ($cart_item = $this->cart_contains()) {
         $order = $this->get_order($cart_item);
         if ($order instanceof WC_Order) {
             foreach ($order->get_fees() as $fee) {
                 $cart->add_fee($fee['name'], $fee['line_total'], abs($fee['line_tax']) > 0, $fee['tax_class']);
             }
         }
     }
 }
WC_Cart