在 WooCommerce 订单总计中将折扣(优惠券)行拆分为多个扣除的成本行 table

Split discount (coupon) row into multiple deducted cost rows in WooCommerce order totals table

如果使用了 2 张优惠券,它会显示 Woocommerce 订单总计中 2 张优惠券的总和 table,而我想分别显示每张优惠券的扣除费用。

例如插入了2张优惠券,目前显示:

我想将其更改为:

来自 WooCommerce 模板文件的路径:order-details.php

foreach ( $order->get_order_item_totals() as $key => $total ) {
    ?>
        <tr>
            <th scope="row"><?php echo esc_html( $total['label'] ); ?></th>
            <td><?php echo ( 'payment_method' === $key ) ? esc_html( $total['value'] ) : wp_kses_post( $total['value'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
        </tr>
        <?php
}

关于如何更改此设置的任何建议?

add_filter('woocommerce_get_order_item_totals', 'woocommerce_get_order_item_totals', 10, 3);

function woocommerce_get_order_item_totals($total_rows, $order, $tax_display) {
    // Loop through order items "coupon"
    $original_dicount_value = $total_rows['discount']['value'];
    $breaked_dicount_value = '';
    $wrapp_table_start = '<table style="width:100%">';
    $i = 1;
    foreach ($order->get_items('coupon') as $item_id => $item) {
        // Get the coupon array data
        $data = $item->get_data();
        $coupon_code = $data['code'];
        $coupon_amt = strip_tags(wc_price($data['discount'] + $data['discount_tax']));
        $breaked_dicount_value .= "<tr>
            <td>coupon$i($coupon_code)</td>
            <td>$coupon_amt</td>
          </tr>";
        $i++;
    }
    $wrapp_table_end = "</table>";
    $total_rows['discount']['value'] = ('' !== $breaked_dicount_value ) ? $wrapp_table_start . $breaked_dicount_value . $wrapp_table_end : $original_dicount_value;
    return $total_rows;
}

没有必要通过 woocommerce_get_order_item_totals 挂钩添加 HTML table 标签,因为它涉及 table 行。

下一个答案删除默认折扣行并将其拆分为包含所需详细信息的多行。

本答案中使用的函数:

所以你得到:

function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {
    // Exit if there is no coupons applied
    if ( sizeof ( $order->get_coupon_codes() ) == 0 ) return $total_rows;
    
    // Initializing
    $new_rows = [];
    
    // Loop through order total lines
    foreach ( $total_rows as $total_key => $total_row ) {
        // Store current rows, except discount
        if ( $total_key != 'discount' ) {
            // Store
            $new_rows[$total_key] = $total_row;
        } else {            
            // For each coupon
            foreach ( $order->get_items('coupon') as $coupon ) {
                // New rows
                $new_rows[$coupon->get_code()] = array(
                    'label' => __( 'Coupon: ', 'woocommerce' ) . $coupon->get_code(),
                    'value' => wc_price( $coupon->get_discount() ),
                );
            }   
        }
    }

    // Overwrite
    $total_rows = $new_rows;

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

结果:


相关: