title: Auto add or update a custom fee via admin edit orders in WooCommerce
body: <p>We have a special case where we invoice our customers for payment after the order has been received instead of having them pay during checkout. Shipping charges are manually calculated and added to the order and then we add a 3% credit card fee on the grand total.</p>
  <p>To automate this process, I created a script that calculates the 3% charge once the shipping charge has been set through the backend and adds this fee item into the order automatically. This works when we add the shipping charge and click save/recalculate the <em>first</em> time.</p>
  <pre><code>add_action( 'woocommerce_order_after_calculate_totals', &quot;custom_order_after_calculate_totals&quot;, 10, 2);
  function custom_order_after_calculate_totals($and_taxes, $order) {
  
      if ( did_action( 'woocommerce_order_after_calculate_totals' ) &gt;= 2 )
      return;
  
      if ( is_admin() &amp;&amp; ! defined( 'DOING_AJAX' ) )
          return;
  
      $percentage = 0.03;
      $total = $order-&gt;get_total();
      $surcharge = $total * $percentage;
      $feeArray = array(
          'name' =&gt; '3% CC Fee',
          'amount' =&gt;  wc_format_decimal($surcharge),
          'taxable' =&gt; false,
          'tax_class' =&gt; ''
      );
  
      //Get fees
      $fees = $order-&gt;get_fees();
      if(empty($fees)){
          //Add fee
          $fee_object = (object) wp_parse_args( $feeArray );
          $order-&gt;add_fee($fee_object);
      } else {
          //Update fee
          foreach($fees as $item_id =&gt; $item_fee){
              if($item_fee-&gt;get_name() == &quot;3% CC Fee&quot;){
                  $order-&gt;update_fee($item_id,$feeArray);
              }
          }
      }
  }
  </code></pre>
  <p>If we accidentally add the wrong shipping cost and try to update it, this code above does get triggered again and updates the fee however <code>$total</code> does not get the new order total from the updated shipping cost and so the fee does not change. Strangely enough, if I try to delete the fee item, a new fee is calculated and is added back with the correct fee amount.</p>
  <p>Anybody know how I can solve this?</p>