Skip to content

Instantly share code, notes, and snippets.

@rajeshsingh520
Last active March 25, 2021 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeshsingh520/82168a0e7bf8178b4af1df5377bf8508 to your computer and use it in GitHub Desktop.
Save rajeshsingh520/82168a0e7bf8178b4af1df5377bf8508 to your computer and use it in GitHub Desktop.
<?php
class pisol_example_of_dynamic_coupon{
function __construct(){
add_action('woocommerce_before_calculate_totals', array($this,'applyDiscountCode'));
add_filter('woocommerce_get_shop_coupon_data', array($this, 'addDiscountCouponData'),10,3);
}
function applyDiscountCode(WC_Cart $cart){
if($this->userSelectedLocalPickup()){
$cart->applied_coupons[] = "pisol-discount";
}
}
function addDiscountCouponData($false, $data, $coupon){
if(!function_exists('WC') || !isset(WC()->cart) || strpos($data,'pisol-discount') === false ) return $false;
if($this->userSelectedLocalPickup()){
$coupon->set_discount_type('fixed_cart');
$coupon->set_amount(10);
return $coupon;
}
WC()->cart->remove_coupon( $data );
return $false;
}
function userSelectedLocalPickup(){
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_no_ajax = $chosen_methods[0];
if ( 0 === strpos( $chosen_shipping_no_ajax, 'local_pickup' ) ) {
return true;
}
return false;
}
}
new pisol_example_of_dynamic_coupon();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment