[英]How to Change Custom Fee order (Ascending/Descending) on cart page (woocommerce )
在 woocommerce 中,我使用以下代碼添加了自定義費用:
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// The percetage
$percent = 10; // 15%
// The cart total
$cart_total = $cart_object->cart_contents_total;
// The conditional Calculation
$fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;
if ( $fee != 0 )
$cart_object->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}
我只想滑動費用順序,就像我想要小計后的“每人費用”和“每人費用”后的“小費”一樣。
WooCommerce 類 WC_Cart_Fees 默認按金額排序費用。
並且為了修改 WooCommerce 的默認行為,您需要覆蓋cart-totals.php
您可以在 woocommerce 插件目錄 woocommerce/templates/cart/cart-totals.php 下找到
在您的子主題名稱 woocommerce/cart 下創建目錄並將該文件復制到此目錄
轉到第 61 行,您可以找到以下代碼:
<?php foreach ( WC()->cart->get_fees() as $fee ) : ?>
<tr class="fee">
<th><?php echo esc_html( $fee->name ); ?></th>
<td data-title="<?php echo esc_attr( $fee->name ); ?>"><?php wc_cart_totals_fee_html( $fee ); ?></td>
</tr>
<?php endforeach; ?>
將該代碼更改為以下內容:
<?php
$array = json_decode(json_encode(WC()->cart->get_fees()), true);
ksort($array); //
foreach ($array as $fee): ?>
<tr class="fee">
<th><?php echo esc_html($fee['name']); ?></th>
<td data-title="<?php echo esc_attr($fee['name']); ?>"><?php echo
$fee['total']; ?></td>
</tr>
<?php endforeach;?>
代碼解釋:
基本上我們在這里所做的是從 WC 類中獲取所有費用,並使用 php 內置函數 json_encode() 將其轉換為數組,以便能夠以我們需要的任何方式對數組進行排序,我使用 ksort() 函數對數組進行排序根據key升序排列數組,然后打印回費用:
這是輸出的屏幕截圖:
您可以按照 kashalo 的說明復制cart-fee.php模板。
但是,如果您唯一需要更改的是費用順序,您可以使用checkout_sort_fees
過濾器覆蓋排序功能。
第一個例子:顛倒順序。
add_action( 'woocommerce_sort_fees_callback', 'reverse_sort_fees' );
function reverse_sort_fees( $order )
{
return -$order;
}
您可以使用更復雜的排序,例如按費用名稱排序。
add_action( 'woocommerce_sort_fees_callback', 'alpha_sort_fees', 10, 3 );
function alpha_sort_fees( $order, $a, $b )
{
return $a->name > $b->name ? 1 : -1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.