Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active July 24, 2024 15:30
Show Gist options
  • Save braddalton/a5508d0756e4fbc0cb7db5259176352f to your computer and use it in GitHub Desktop.
Save braddalton/a5508d0756e4fbc0cb7db5259176352f to your computer and use it in GitHub Desktop.
Buy x Amount Get x Number Free WooCommerce Full tutorial and support @ https://wpsites.net/?p=116705
add_action('woocommerce_cart_calculate_fees', 'buy_ten_get_two_free', 10, 1 );
function buy_ten_get_two_free( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Set HERE your targeted variable products IDs
$targeted_product_ids = array( 185 );
$each_n_items = 10; // Number of items required to get a free one
$free_items_count = 2; // Number of free items to give
$discount = 0; // Initializing
$count_items = 0; // Initializing counter for eligible items
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$qty = intval( $cart_item['quantity'] );
$count_items += $qty;
}
}
// Calculate number of free items
$free_items = floor( $count_items / $each_n_items ) * $free_items_count;
// Calculate total price of items eligible for discount
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$qty = intval( $cart_item['quantity'] );
$price = floatval( $cart_item['data']->get_price() );
// Calculate how many items are eligible for discount
$eligible_qty = min( $qty, $free_items );
// Calculate the discount based on eligible quantity
$discount += $eligible_qty * $price;
// Deduct the eligible items from free_items count
$free_items -= $eligible_qty;
}
}
if ( $discount > 0 ) {
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("Buy 10 Get 2 Free"), 'notice');
// Apply the discount
$cart->add_fee( __("Buy 10 Get 2 Free"), -$discount, true );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment