首页 > 解决方案 > 如何在购物车页面(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 );
}

我只想刷一下费用顺序,就像我想要在小计之后的“每人费用”和“每人费用”之后的“小费”一样。

这是附上的截图

标签: phpwordpresswoocommercehook-woocommerce

解决方案


WooCommerce 类 WC_Cart_Fees 默认按金额对费用进行排序。

参考 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升序排列数组,然后打印回费用:

这是输出的屏幕截图:

在此处输入图像描述


推荐阅读