繁体   English   中英

如何更改购物车页面上的自定义费用顺序(升序/降序)(woocommerce)

[英]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 默认按金额排序费用。

参考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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM