Last active
June 7, 2024 15:00
-
-
Save Acephalia/ddb2ca025188a5b4db14c362022b998c to your computer and use it in GitHub Desktop.
WooCommerce Buy 3 get 1 Free For Variations/Attributes
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
/** | |
* @snippet WooCommerce Buy 3 get 1 Free For Variations/Attributes | |
* @how-to https://insomniainc.com/code-snippets/woocommerce/woocommerce-buy-3-get-1-free-for-variations-attributes/ | |
* @author u/acephaliax | |
* @compatiblity Last tested on WooCommerce 8.9.2 | |
* @community r/wordpress, r/woocommerce | |
* @caffeinate https://buymeacoffee.com/acephaliax | |
*/ | |
// Hook to calculate fees in the cart | |
add_action( 'woocommerce_cart_calculate_fees', 'insomniainc_variation_party_discount' ); | |
// Function to calculate attribute discount | |
function insomniainc_variation_party_discount( $cart ) { | |
// Define the attribute name (e.g. "Colour") | |
$attribute_name = 'Colour'; | |
// Define the term names for the attribute (e.g. "Blue", "Black", "White") | |
$terms = array('Blue', 'Black', 'White'); | |
// Loop through each term | |
foreach ( $terms as $term ) { | |
$term_count = 0; | |
$term_product = null; | |
$discount_count = 0; | |
// Loop through each item in the cart | |
foreach ( $cart->get_cart() as $cart_item ) { | |
$product = $cart_item['data']; | |
$product_name = $product->get_name(); | |
// Check if the product name contains the term | |
if ( strpos( $product_name, $term )!== false ) { | |
$term_count++; | |
$term_product = $product; // store the product for later use | |
} | |
} | |
// If the term count is greater than or equal to the threshold, apply the discount | |
if ( $term_count >= 4 ) { // Change this number to adjust the threshold (e.g. 3, 5, etc.) | |
$discount_count = floor( $term_count / 4 ); // Change this number to adjust the discount ratio (e.g. 3, 5, etc.) | |
$product_price = $term_product->get_price(); // Get price of one product with the term | |
// Dynamic discount text with plural support | |
if ( $discount_count > 1 ) { | |
$discount_text = $discount_count. ' Free '. $term.'s'; // Append 's' for plural | |
} else { | |
$discount_text = $discount_count. ' Free '. $term; // Singular | |
} | |
$cart->add_fee( $discount_text, -$product_price * $discount_count ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For reddit request: https://www.reddit.com/r/Wordpress/comments/1d7wyux/buy_2_get_1_free_plugin_for_woocommerce/