I know how to add a line item programmatically, but I can't seem to find a way to specifically add a custom commerce fee in PHP. Commerce fees seem to register in two locations in the order array: Once under commerce_line_items, and once under commerce_order_total (See attached image). They are different than a regular line item in that they don't show up as products, but rather in the order totals box at the end of the order. The fee shown in the attachment is one that has been entered using the Edit form in the admin section. I need to add one in code. Any ideas?
What you're seeing is the commerce price component and the relevant line item that were added to the order. It gets added by the
commerce_fees_apply() function from
So, if you're wanting to programmatically add a $5 fee to an order, then you can do so like this:
$order_wrapper = entity_metadata_wrapper('commerce_order', $order); $fee = commerce_fees_load('machine_name_of_fee'); commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
'machine_name_of_fee' would be the machine name of the fee that was created using the UI. Remember that the 3rd argument will be an amount and not a decimal. You'll also need to pass in the currency code. If you're wanting it to take the value of the currency code of the order, you could replace
'USD' with something like.
$currency_code = $order->commerce_order_total[LANGUAGE_NONE]['currency_code']; commerce_fees_apply($order_wrapper, $fee, 500, $currency_code);
If you stucked in why #1 doesn't work, you should try something like this:
$order_wrapper = entity_metadata_wrapper('commerce_order', $order); $fee = 'FEE_MACHINE_NAME'; commerce_fees_apply($order_wrapper, $fee, 500, 'USD'); $order_wrapper->save();