我使用此代碼向特定產品 ID 添加額外費用。問題是我只能向不同的產品 ID 添加一項費用。
add_action('woocommerce_cart_calculate_fees', 'add_fees_on_ids');
function add_fees_on_ids() {
if (is_admin() && !defined
('DOING_AJAX')) {return;}
foreach( WC()->cart->get_cart() as $item_keys => $item ) {
if( in_array( $item['product_id'],
fee_ids() )) {
WC()->cart->add_fee(__('ADDITIONAL FEE:'), 5);
}
}
}
function fee_ids() {
return array( 2179 );
}
我需要為不同的產品添加不同的費用 - 例如:
- 產品 ID 為 1234 的產品 1 將收取“xx”額外費用。
- 產品 ID 為 5678 的產品 2 將收取“xx”額外費用。
使用此代碼,我只能為不同的產品設定一項費用。如何在 WooCommerce 中為不同的產品添加不同的費用?
uj5u.com熱心網友回復:
你好,謝謝大家!我找到了解決問題的方法。我只是多次復制下面描述的代碼,因為我對不同的產品有不同的數量并進行更改:
add_action('woocommerce_cart_calculate_fees', 'add_fees_on_ids');
function add_fees_on_ids() {
if (is_admin() && !defined
('DOING_AJAX')) {return;}
foreach( WC()->cart->get_cart() as $item_keys => $item ) {
if( in_array( $item['product_id'],
fee_ids() )) {
WC()->cart->add_fee(__('ADDITIONAL FEE:'), 5);
}
}
}
function fee_ids() {
return array( 2179 );
}
我改add_fees_on_ids到add_fees_on_ids_1和fee_ids來fee_ids_1
和ADDITIONAL FEE:到ADDITIONAL FEE 1:
我知道對于某些人來說,它可能看起來不專業,但它可以解決我的問題。
uj5u.com熱心網友回復:
有幾種方法。例如,您確實可以向管理產品設定添加自定義欄位。
但這并不一定很復雜,為此安裝一個額外的插件太牽強了!
多次添加相同的代碼也是一個壞主意,因為這樣您將多次瀏覽購物車。這不僅會減慢您的網站速度,還會最終導致錯誤。
添加一個陣列,您不僅可以確定產品 ID,還可以根據陣列鍵立即確定額外費用,這在我看來是最簡單有效的方法。
所以你得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Add in the following way: Additional fee => Product ID
$settings = array(
10 => 1234,
20 => 5678,
5 => 30,
20 => 813,
2 => 815,
);
// Initialize
$additional_fee = 0;
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// In array, get the key as well
if ( false !== $key = array_search( $product_id, $settings ) ) {
$additional_fee = $key;
}
}
// If greater than 0, so a matching product ID was found in the cart
if ( $additional_fee > 0 ) {
// Add additional fee (total)
$cart->add_fee( __( 'Additional fee', 'woocommerce' ), $additional_fee, false );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
uj5u.com熱心網友回復:
I. 您可以使用 WordPress 插件“高級自定義欄位”:
- 安裝插件
- 設定一個標題為“Product with fee”的欄位組,并將其位置規則設定為“Post Type” => “is equal to” => “Product”
- “欄位型別”“文本”的“ 添加欄位”并注意其“名稱”(不是“標簽”)以供以后檢查,例如“費用”
- 在相應的 WooCommerce 產品帖子的費用元欄位中設定費用值
- 在
'woocommerce_cart_calculate_fees'購物車產品的鉤子回呼回圈中,檢查具有名為“fee”的元欄位的設定值的產品,并在該條件下添加您的費用添加代碼:
if (get_field( "fee" )) { // get_field() returns false if empty aka not set from admin area
// fee adding code for single product in cart
};
二、或者,您可以通過添加和顯示 WooCommerce 自定義產品元欄位來實作這一點,如這里深入描述的那樣:
https://www.cloudways.com/blog/add-custom-product-fields-woocommerce/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351208.html
標籤:php WordPress的 求购 大车 费用
