MichelH

Discount depends on Woocemmerce payment method

Apr 5th, 2023 (edited)
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | Source Code | 0 0
  1. add_action( 'woocommerce_cart_calculate_fees', 'wc_payment_based_discount', 10, 1 );
  2. function wc_payment_based_discount( $cart ) {
  3.  
  4.   if ( is_admin() && ! defined( 'DOING_AJAX' ) )
  5.     return;
  6.  
  7.   // Check if a coupon code has been applied
  8.   if ( WC()->cart->has_discount() )
  9.     return;
  10.  
  11.   // Check if the product "Wallet Topup" is in the cart
  12.   $wallet_topup_found = false;
  13.   foreach ( $cart->get_cart() as $cart_item ) {
  14.     if ( $cart_item['data']->get_name() == 'Wallet Topup' ) {
  15.       $wallet_topup_found = true;
  16.       break;
  17.     }
  18.   }
  19.  
  20.   if ( $wallet_topup_found )
  21.     return;
  22.    
  23.     // Check if the product is on sale
  24. $product_on_sale = false;
  25. foreach ( $cart->get_cart() as $cart_item ) {
  26.   if ( $cart_item['data']->is_on_sale() ) {
  27.     $product_on_sale = true;
  28.     break;
  29.   }
  30. }
  31.  
  32. if ( $product_on_sale )
  33.   return;
  34.  
  35.   // Get chosen payment method
  36.   $payment_method = WC()->session->get( 'chosen_payment_method' );
  37.  
  38.   if ( $payment_method == 'wallet' ) {
  39.     $discount_percent = 2;
  40.   } elseif ( $payment_method == 'cod' ) {
  41.     $discount_percent = 2;
  42.   } else {
  43.     $discount_percent = 0;
  44.   }
  45.  
  46.   // Calculate discount amount
  47.   $discount_amount = $cart->get_subtotal() * ( $discount_percent / 100 );
  48.   $cart->add_fee( 'Discount', - $discount_amount, true );
  49. }
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment