自定义特定运输方式费用不应用于 WooCommerce 总额

问题描述 投票:0回答:1

通过以下代码,我根据补贴获得了正确显示的运输方式成本(请参阅此线程

add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_method_full_label', 10, 2 );
function custom_shipping_method_full_label( $label, $method ) {
    if ( !in_array( $method->get_method_id(), array( 'free_shipping', 'local_pickup' ), true ) && 0 < $method->cost ) {
        $label    = $method->get_label(); // Get shipping label without cost
        $new_cost = $method->cost - get_total_subsidies( WC()->cart->get_cart() );

        if ( $new_cost > 0 ) {
            $method->cost = $new_cost;
            $label .= ': ' . wc_price( $new_cost );
        } else {
            $method->cost = 0;
            $label .= ': ' .' <span class="free-cost">' . __('Free!', 'woocommerce').'</span>';
        }
    }
    return $label;
}

但考虑到原始运输方式成本,它不会扩展到总计计算。

我需要新的成本作为购物车和结账页面计算总计的当前成本。

php wordpress woocommerce checkout shipping-method
1个回答
0
投票

要处理运费重新计算并显示它们,您需要将当前代码替换为以下代码:

// Utility function: Reset shipping taxes
function zero_taxes( $tax ) {
    return 0;
}


// Set zero shipping cost for prepaid orders
add_action('woocommerce_package_rates', 'disable_shipping_cost_for_prepaid_orders', 10, 2);
function disable_shipping_cost_for_prepaid_orders($rates, $package) {
    $total_subsidies = get_total_subsidies( $package['contents'] );
    
    if ( ! $total_subsidies ) {
        return $rates;
    }

    // Loop through shipping rates
    foreach ($rates as $rate_key => $rate) {
        if( ! in_array( $rate->method_id, array( 'free_shipping', 'local_pickup' ), true ) && $rate->cost > 0 ) {
            $new_cost = $rate->cost - $total_subsidies;

            if ( $new_cost > 0 ) {
                $rates[$rate_key]->cost = $new_cost; // Set the new cost
            } else {
                $rates[$rate_key]->cost   = 0; // Null the cost
                $rates[$rate_key]->taxes  = array_map('zero_taxes', $rate->taxes);  // Null shipping costs taxes
                $rates[$rate_key]->label .= ': ' .' <span class="free-cost">' . __('Free!', 'woocommerce') . '</span>'; // Custom displayed label
            }
        }
    }
    return $rates;
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

重要提示:清空购物车以刷新运输方式缓存数据。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.