php - 在 WooCommerce 订单和电子邮件通知中按名称对费用进行排序
问题描述
我需要按名称而不是 WooCommerce 订单中的默认价格对费用进行排序。
在 Woocommerce 购物车和结帐页面回答代码中使用以不同方式重新排序多项费用,我设法在购物车和结帐页面中按名称对费用进行排序。但它不适用于订单确认和发送的电子邮件。
谢谢您的帮助。
解决方案
更新
要按客户订单和电子邮件通知的名称对费用进行排序,您将使用以下内容:
// Custom function that sort displayed fees by name on order items
function wc_get_sorted_order_item_totals_fee_rows( &$total_rows, $tax_display, $order ) {
$fees = $order->get_fees();
if ( $fees ) {
$fee_names = []; // initializing
// First Loop
foreach ( $fees as $fee_id => $fee ) {
$fee_names[$fee_id] = $fee->get_name();
}
asort($fee_names); // Sorting by name
// 2nd Loop
foreach ( $fee_names as $fee_id => $fee_name ) {
$fee = $fees[$fee_id];
if ( apply_filters( 'woocommerce_get_order_item_totals_excl_free_fees', empty( $fee['line_total'] ) && empty( $fee['line_tax'] ), $fee_id ) ) {
continue;
}
$total_rows[ 'fee_' . $fee->get_id() ] = array(
'label' => $fee->get_name() . ':',
'value' => wc_price( 'excl' === $tax_display ? $fee->get_total() : $fee->get_total() + $fee->get_total_tax(), array( 'currency' => $order->get_currency() ) ),
);
}
}
}
// Display sorted fees by name everywhere on orders and emails
add_filter( 'woocommerce_get_order_item_totals', 'display_date_custom_field_value_on_order_item_totals', 10, 3 );
function display_date_custom_field_value_on_order_item_totals( $total_rows, $order, $tax_display ){
// Initializing variables
$new_total_rows = $item_fees = [];
// 1st Loop - Check for fees
foreach ( $total_rows as $key => $values ) {
if( strpos($key, 'fee_') !== false ) {
$item_fees[] = $key;
}
}
if( count($item_fees) > 1 ) {
// 2nd Loop - Remove item fees total lines
foreach ( $item_fees as $key ) {
unset($total_rows[$key]);
}
$key_start = isset($total_rows['shipping']) ? 'shipping' : ( isset($total_rows['discount']) ? 'discount' : 'cart_subtotal' );
// 3rd Loop - loop through order total rows
foreach( $total_rows as $key => $values ) {
$new_total_rows[$key] = $values;
// Re-inserting sorted fees
if( $key === $key_start ) {
wc_get_sorted_order_item_totals_fee_rows( $new_total_rows, $tax_display, $order );
}
}
return $new_total_rows;
}
return $total_rows;
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
推荐阅读
- javascript - 找到满足某些条件的数组的子集
- xml - 在 xml 元素中导入命名空间
- excel - 在此示例中如何避免 VBA 中的选择/活动语句?
- java - Spring Boot 将 OAuth2 和 HttpBasic Login 与自定义表单相结合
- c - 启用内核 TLS 选项时,setsockopt 失败
- google-cloud-platform - 查找与存储桶关联的服务帐户的权限
- c++ - C++ 访问基于 1 而不是 0 的数组,通过在编译时移位
- amazon-web-services - CloudFormation 通行证标签
- java - 在 dynamoDB AWS 的 for 循环中保存数据
- c# - 有没有办法在忽略空格的同时使用 OrderBy 对字符串进行排序?