Local pickup shipping option custom percentage discount in Woocommerce

自闭症网瘾萝莉.ら 提交于 2020-05-16 12:39:54

问题


My WooCommerce checkout page gives some shipping options:

  • Flat Rate (costs money)
  • Local Pickup (free).

How can I give a 5% discount on total order cost if a customer chooses Local Pickup shipping method?


回答1:


The following code will add a discount of 5% to cart subtotal for Local Pickup chosen shipping method:

add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_pickup_shipping_method', 10, 1 );
function custom_discount_for_pickup_shipping_method( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 5; // <=== Discount percentage

    $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
    $chosen_shipping_method    = explode(':', $chosen_shipping_method_id)[0];

    // Only for Local pickup chosen shipping method
    if ( strpos( $chosen_shipping_method_id, 'local_pickup' ) !== false ) {
        // Calculate the discount
        $discount = $cart->get_subtotal() * $percentage / 100;
        // Add the discount
        $cart->add_fee( __('Pickup discount') . ' (' . $percentage . '%)', -$discount );
    }
}

Code goes in function.php file of your active child theme (active theme). Tested and works.



来源:https://stackoverflow.com/questions/52630355/local-pickup-shipping-option-custom-percentage-discount-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!