php - 如何在购物车页面(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升序排列数组,然后打印回费用:
这是输出的屏幕截图:
推荐阅读
- postgresql - 如何使用 AWS DMS 迁移具有默认值、约束和序列的表以进行 postgres 到 postgres 的迁移?
- powershell - System Center Configuration Manager - PowerShell 远程处理
- bash - 为什么 4 张图像中的 1 张没有被推送到 ECR
- ios - 相同大小的物体总是卡在镜头前
- gradle - Gradle Task - 无法在 groovy 中执行斐波那契数列
- matlab - Mosek 中的二次和线性约束(来自 Matlab)
- r - 'path_matrix' 必须是下三角矩阵
- javascript - 在js中声明的单击按钮不起作用
- ansible - 使用 Ansible 时如何将选项传递给 dnf
- html - 在 html 中内联 css标记反应