该WC_Abstract_Legacy_Order
方法add_fee()
已弃用,并且Classset_fee()
不存在该方法(exist only for and classes)。WC_Order
WC_Cart
WC_API_Orders
自 Woocommerce 3 以来,要以编程方式向订单添加费用,这有点复杂。有一些参数可以设置为费用名称、税务状态、税级(如果需要)和费用金额(不含税)。
此外,为了进行税收计算,根据税收设置,您需要设置一个数组,其中包含最低限度的客户国家代码(如果税收基于国家/地区)
假设费用金额变量名称$imported_total_fee
在下面的代码中:
$order->set_date_created($creation_tsz);
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->set_currency('GBP');
## ------------- ADD FEE PROCESS ---------------- ##
// Get the customer country code
$country_code = $order->get_shipping_country();
// Set the array for tax calculations
$calculate_tax_for = array(
'country' => $country_code,
'state' => '',
'postcode' => '',
'city' => ''
);
// Get a new instance of the WC_Order_Item_Fee Object
$item_fee = new WC_Order_Item_Fee();
$item_fee->set_name( "Fee" ); // Generic fee name
$item_fee->set_amount( $imported_total_fee ); // Fee amount
$item_fee->set_tax_class( '' ); // default for ''
$item_fee->set_tax_status( 'taxable' ); // or 'none'
$item_fee->set_total( $imported_total_fee ); // Fee amount
// Calculating Fee taxes
$item_fee->calculate_taxes( $calculate_tax_for );
// Add Fee item to the order
$order->add_item( $item_fee );
## ----------------------------------------------- ##
$order->calculate_totals();
$order->update_status('on-hold');
$order->save();
经过测试并完美运行。