Created
November 23, 2023 06:31
-
-
Save Acephalia/f575754dcc54185bc8eff98b1f13992a to your computer and use it in GitHub Desktop.
Adjust price based on order quantity for specific product ID
This file contains 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
// Adjust price based on order quantity for specific product ID by u/acephaliax | |
function adjust_product_price_based_on_quantity( $cart ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { | |
return; | |
} | |
// Target product ID | |
$target_product_id = 828; | |
// Get the quantity of the targeted product in the cart | |
$quantity = 0; | |
foreach ( $cart->get_cart() as $cart_item ) { | |
if ( $cart_item['product_id'] === $target_product_id ) { | |
$quantity += $cart_item['quantity']; | |
} | |
} | |
// Set price based on quantity ranges | |
if ( $quantity <= 5 ) { | |
$new_price = 10; | |
} elseif ( $quantity <= 10 ) { | |
$new_price = 15; | |
} elseif ( $quantity <= 15 ) { | |
$new_price = 20; | |
} | |
// Update the product price | |
if ( $new_price ) { | |
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { | |
if ( $cart_item['product_id'] === $target_product_id ) { | |
$cart->cart_contents[$cart_item_key]['data']->set_price( $new_price ); | |
} | |
} | |
} | |
} | |
add_action( 'woocommerce_before_calculate_totals', 'adjust_product_price_based_on_quantity' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment