wordpress 运费基于woocommerce上的产品数量

ny6fqffe  于 2023-01-16  发布在  WordPress
关注(0)|答案(3)|浏览(187)

我想在我的woocommerce主题上设置运输成本数量明智。我想做这个选项:
对于1至5个产品运输成本将是15%。超过5个产品鞭打成本将是6.99美元。
我可以添加此航运选项没有插件?

abithluo

abithluo1#

您需要将一个函数与woocommerce_calculate_totals操作挂钩,该操作在计算最终购物车总额之前触发。woocommerce_calculate_totals操作提供WC_Cart示例,您可以根据需要在该示例上执行操作。

add_action('woocommerce_calculate_totals', 'modify_shipping_totals');

function modify_shipping_totals($cart) {
    if($cart->get_cart_contents_count() < 6) {
        $cart->shipping_total = ( 15/100 ) * $this->cart_contents_total; 
        // shipping cost will be 15% of cart content total

        // you may also want to modify the shipping tax.

        $cart->shipping_tax_total = 0; 
    } else {
        $cart->shipping_total = 6.99;
        $cart->shipping_tax_total = 0;
    }

}

有关可更改变量的更多参考,请参阅WC_Cart文档。

gev0vcfq

gev0vcfq2#

// **Note**: This code is working only when you set Flat rate Settings 
// cost value is 1

add_filter( 'woocommerce_package_rates', 'custom_package_rates', 10, 2 );
 function custom_package_rates( $rates, $packages ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    $cart_count = WC()->cart->get_cart_contents_count();
    $cart_total =  WC()->cart->cart_contents_total;

    foreach($rates as $rate_key => $rate_values ) {
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;

        if( $method_id == 'flat_rate' ){
            if( $cart_count < 99 ){
                $flat_rate_value = 4.95; //"Applay Flat rate less then 99 quatity"
                $cart_10_percent = 0; // No percent discount
            }   
            if( $cart_count > 99 ){
                $flat_rate_value = 9.95; // "Applay Flat rate greater then 99 quatity"
                $cart_10_percent = 0; // No percent discount
            }
            $rate_cost = $flat_rate_value > $cart_10_percent ? $flat_rate_value - $cart_10_percent : 0;

            // Set the new calculated rate cost
            $rates[$rate_id]->cost = number_format( $rates[$rate_id]->cost * $rate_cost, 2 );

        }
    }
    return $rates;
}
kupeojn6

kupeojn63#

Pranav解决方案可以在init钩子内调用add_action,如下所示:

function init_shop(){
    add_action('woocommerce_calculate_totals', 'modify_shipping_totals', 10);
}
add_action( 'init', 'init_shop');

相关问题