Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

php - Shipping discount based on chosen payment method in WooCommerce

I'm currently trying to apply a discount on shipping if a customer chooses a certain payment method.

For some reason, this applies the discount regardless of which payment method is chosen.

The code I'm using in functions.php is:

function filter_woocommerce_package_rates( $rates, $package ) {
    
    $min = 25;
    $min2 = 25;
    $max = 50;
    $discount_percent = 50;
    $payment_method = 'clearpay';
    $chosen_payment_method = WC()->session->get('chosen_payment_method');

    // Get cart total
    $cart_total = WC()->cart->cart_contents_total;

    // Condition
    if ( $cart_total >= $min && $cart_total <= $max && $payment_method == $chosen_payment_method ) {
        // (Multiple)
        foreach ( $rates as $rate_key => $rate ) {
            // Get rate cost            
            $cost = $rates[$rate_key]->cost;
            
            // Set rate cost
            $rates[$rate_key]->cost = $cost - ( ( $cost * $discount_percent ) / 100 );
        }
        
        wc_add_notice( 
            sprintf( 'Congratulations! Your shipping is now 50&#37; off!' , 
                wc_price( WC()->cart->total ), 
                wc_price( $minimum )
            ), 'success' 
        );
        
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
do_action( 'woocommerce_set_cart_cookies',  true );

Any idea what’s wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I'm doing in order to get flat discount amounts for different payment methods

You can adapt it to your case

add_action( 'woocommerce_cart_calculate_fees','mlnc_add_discount', 20, 1 );

function mlnc_add_discount( $cart_object ) {

$label= __('');
$discount = 0;

$chosen_payment_method = WC()->session->get('chosen_payment_method'); //get the selected payment method

switch($chosen_payment_method){
case 'paypal':    
$label = __( "PayPal Discount" );
// The discount amount to apply
$discount = 5;
break;
case 'bacs':    
$label = __( "Direct Bank Transfer Discount" );
// The discount amount to apply
$discount = 10;
break; 
case 'cod':    
$label = __( "Cash on Delivery Discount" );
// The discount amount to apply
$discount = 0;
break; 
}

// Add the discount
$cart_object->add_fee( $label, - $discount, false );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...