Created
November 16, 2021 17:15
-
-
Save mlbd/9e15c2fc6c7bde646e58daff9a07242c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* get percentage by quantity | |
*/ | |
function sakib_get_discount( $quantity ) { | |
switch ($quantity) { | |
case 6: | |
$discount = 20; | |
break; | |
case 10: | |
$discount = 30; | |
break; | |
default: | |
$discount = 0; | |
} | |
return $discount / 100; | |
} | |
/** | |
* Set dynamic product price or discount by quantity | |
* | |
* @param $cart_object | |
* | |
* @return void | |
*/ | |
function sakib__cart_item_price( $cart_object ){ | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) | |
return; | |
// Required since Woocommerce version 3.2 for cart items properties changes | |
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) | |
return; | |
foreach ( $cart_object->get_cart() as $cart_item ) { | |
// discounts by quantity | |
$new_price = $cart_item['data']->get_regular_price() - ( $cart_item['data']->get_regular_price() * sakib_get_discount( (int) $cart_item['quantity'] ) ); | |
$cart_item['data']->set_price( $new_price ); | |
} | |
} | |
add_action( 'woocommerce_before_calculate_totals', 'sakib__cart_item_price', 20, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment