Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Last active June 7, 2024 15:00
Show Gist options
  • Save Acephalia/ddb2ca025188a5b4db14c362022b998c to your computer and use it in GitHub Desktop.
Save Acephalia/ddb2ca025188a5b4db14c362022b998c to your computer and use it in GitHub Desktop.
WooCommerce Buy 3 get 1 Free For Variations/Attributes
/**
* @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 );
}
}
}
@Acephalia
Copy link
Author

Acephalia commented Jun 7, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment