Add Fee to WooCommerce Backend by Category ID

Viewed 25

This will add a charge(percentage) to a WooCommerce order on backend edit order(admin access and not the frontend where cart would be shown to customer) Basically, creating an order manually from the backend.

How can I target the fee by category-ID as opposed to having it apply on the complete total before taxes which is exactly what it does now, as is. Note: Actual fee is optional and pulled from an acf value(vendor decides the fee) and works

add_action( 'woocommerce_order_after_calculate_totals', 
"engx_custom_calculate_totals_add_tire_new_fee", 10, 2 );
function engx_custom_calculate_totals_add_tire_new_fee( $and_taxes, $order ) {
if ( did_action( 'woocommerce_order_after_calculate_totals' ) >= 2 )
    return;

//GET ACF Field Value
$fees = get_field("fees", 5667); 
$shop_supply_percentage = $fees["shop_supply_percentage"];   
    
$percentage = $shop_supply_percentage; // Fee percentage 0.05 -- use this acf value as the shop supply percentage

$fee_data   = array(
    'name'       => __('New Tire Fee'),
    'amount'     => wc_format_decimal( $order->get_total() * $percentage ),
    'tax_status' => 'taxable',        //Add tax
    'tax_class'  => ''     
    
);

$fee_items  = $order->get_fees(); // Get fees

// Add fee
if( empty($fee_items) ){
    $item = new WC_Order_Item_Fee(); // Get an empty instance object

    $item->set_name( $fee_data['name'] );
    $item->set_amount( $fee_data['amount'] );
    $item->set_tax_class($fee_data['tax_class']);
    $item->set_tax_status($fee_data['tax_status']);
    $item->set_total($fee_data['amount']);

    $order->add_item( $item );
    $item->save(); // (optional) to be sure
}
// Update fee
else {
    foreach ( $fee_items as $item_id => $item ) {
        if( $item->get_name() === $fee_data['name'] ) {
      //      $item->remove_item( $item_id ); // Remove the item

            $item = new WC_Order_Item_Fee(); // Get an empty instance object

            $item->set_name( $fee_data['name'] );
            $item->set_amount( $fee_data['amount'] );
            $item->set_tax_class($fee_data['tax_class']);
            $item->set_tax_status($fee_data['tax_status']);
            $item->set_total($fee_data['amount']);

      //      $order->add_item( $item );
            $item->save(); // (optional) to be sure
        }
    }
}
}
0 Answers
Related