我正在使用如何在 WooCommerce 購物車答案代碼(第 2 部分)中為不同產品添加額外費用。此代碼用于向用其 ID 描述的產品添加額外費用。
在現有答案中,我已替換:
// Settings
$settings = array(
array(
'product_id' => 30,
'amount' => 5,
'name' => __( 'Additional service fee', 'woocommerce' ),
),
array(
'product_id' => 813,
'amount' => 10,
'name' => __( 'Packing fee', 'woocommerce' ),
),
array(
'product_id' => 815,
'amount' => 15,
'name' => __( 'Another fee', 'woocommerce' ),
),
);
和
// Settings
$settings = array(
array(
'product_id' => __(123, 456, 789),
'amount' => 10,
'name' => __( 'Additional service fee', 'woocommerce' ),
),
array(
'product_id' => __(987, 654, 321),
'amount' => 20,
'name' => __( 'Additiona packing fee', 'woocommerce' ),
),
array(
'product_id' => __(445, 556, 555),
'amount' => 30,
'name' => __( 'Additinal specific fee', 'woocommerce' ),
),
);
目前,如果我添加兩個屬于同一“附加費”類別的產品,例如“附加服務費”只顯示一次金額,不計算在內。
我的問題是如何更改代碼,以便通過添加多個屬于同一“附加費用”類別的產品 - 考慮該類別的費用總和。
uj5u.com熱心網友回復:
該__() WordPress的功能檢索翻譯,因此具有無關添加多個productIDs。相反,您可以將多個產品 ID 添加為一個陣列。
注意:該total_amount設定用作跟蹤總金額的計數器,因此不應更改!
注意:我添加了額外的代碼,也將產品數量考慮在內。如果不適用。只需洗掉$quantity = $cart_item['quantity'];并更改$setting['amount'] * $quantity;為$setting['amount'];
所以你得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings (multiple settings arrays can be added/removed if desired)
$settings = array(
array(
'product_id' => array( 30, 813, 815 ),
'amount' => 5,
'name' => __( 'Additional service fee', 'woocommerce' ),
'total_amount' => 0,
),
array(
'product_id' => array( 817, 819, 820 ),
'amount' => 25,
'name' => __( 'Packing fee', 'woocommerce' ),
'total_amount' => 0,
),
array(
'product_id' => array( 825 ),
'amount' => 100,
'name' => __( 'Another fee', 'woocommerce' ),
'total_amount' => 0,
),
);
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Get quantity
$quantity = $cart_item['quantity'];
// Loop trough settings array (determine total amount)
foreach ( $settings as $key => $setting ) {
// Search for the product ID
if ( in_array( $product_id, $settings[$key]['product_id'] ) ) {
// Addition
$settings[$key]['total_amount'] = $setting['amount'] * $quantity;
}
}
}
// Loop trough settings array (output)
foreach ( $settings as $setting ) {
// Greater than 0
if ( $setting['total_amount'] > 0 ) {
// Add fee
$cart->add_fee( $setting['name'], $setting['total_amount'], false );
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352309.html
標籤:php WordPress的 求购 大车 费用
