更改 WooCommerce 中显示的运费总额

Change the displayed shipping total in WooCommerce

我需要以编程方式更改运费:

<?php
   $percentage = 50;
   $current_shipping_cost = WC()->cart->get_cart_shipping_total();
   echo $current_shipping_cost * $percentage / 100;
?>

不幸的是它不起作用,我总是得到 0 (零)

如何根据计算的折扣百分比更改显示的运费总额?

以下将根据百分比显示运费总额。有两种方式:

1) 第一种方式 使用自定义函数。

在您的活动子主题(或活动主题)的 function.php 文件中:

function wc_display_cart_shipping_total( $percentage = 100 )
{
    $cart  = WC()->cart;
    $total = __( 'Free!', 'woocommerce' );

    if ( 0 < $cart->get_shipping_total() ) {
        if ( $cart->display_prices_including_tax() ) {
            $total = wc_price( ( $cart->shipping_total + $cart->shipping_tax_total ) * $percentage / 100 );
            if ( $cart->shipping_tax_total > 0 && ! wc_prices_include_tax() ) {
                $total .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
            }
        } else {
            $total = wc_price( $cart->shipping_total * $percentage / 100  );
            if ( $cart->shipping_tax_total > 0 && wc_prices_include_tax() ) {
                $total .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat()  . '</small>';
            }
        }
    }
    return  $totals;
}

用法:

<?php echo wc_display_cart_shipping_total(50); ?>

2) 第二种方式 带过滤挂钩。

在您的活动子主题(或活动主题)的 function.php 文件中:

add_filter( 'woocommerce_cart_shipping_total', 'woocommerce_cart_shipping_total_filter_callback', 11, 2 );
function woocommerce_cart_shipping_total_filter_callback( $total, $cart )
{
    // HERE set the percentage
    $percentage = 50;

    if ( 0 < $cart->get_shipping_total() ) {
        if ( $cart->display_prices_including_tax() ) {
            $total = wc_price( ( $cart->shipping_total + $cart->shipping_tax_total ) * $percentage / 100 );
            if ( $cart->shipping_tax_total > 0 && ! wc_prices_include_tax() ) {
                $total .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
            }
        } else {
            $total = wc_price( $cart->shipping_total * $percentage / 100  );
            if ( $cart->shipping_tax_total > 0 && wc_prices_include_tax() ) {
                $total .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat()  . '</small>';
            }
        }
    }
    return  $totals;
}

用法:

<?php echo WC()->cart->get_cart_shipping_total(); ?>