Skip to content

Instantly share code, notes, and snippets.

@MattRyanCo
Created June 14, 2021 15:47
Show Gist options
  • Save MattRyanCo/5603a9a24783aa3a2d6026364a20ffc7 to your computer and use it in GitHub Desktop.
Save MattRyanCo/5603a9a24783aa3a2d6026364a20ffc7 to your computer and use it in GitHub Desktop.
WooCommerce Buy One Get One 50% off through a set date
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
function add_custom_discount_2nd_at_50( $wc_cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Get out of here if we are past the specific date set in the dateDifference function below.
if ( 0 > tew_dateDifferenceEOM( '2021-06-30') ) return;
$discount = 0;
$items_prices = array();
// Set HERE your targeted variable product ID
$targeted_product_id = array( 524, 705, 833, 835 );
foreach ( $wc_cart->get_cart() as $key => $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_id ) ){
$qty = intval( $cart_item['quantity'] );
for( $i = 0; $i < $qty; $i++ )
$items_prices[] = floatval( $cart_item['data']->get_price());
}
}
$count_items_prices = count($items_prices);
if( $count_items_prices > 1 ) foreach( $items_prices as $key => $price )
if( $key % 2 == 1 ) $discount -= number_format($price / 2, 2 );
if( $discount != 0 ){
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("You get 50% of discount on the 2nd item"), 'notice');
// The discount
$wc_cart->add_fee( 'Discount 2nd at 50%', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
function tew_dateDifferenceEOM($date_eom, $differenceFormat = '%a' )
{
$datetime1 = date_create($date_eom);
$datetime2 = date_create( date("Y-m-d") );
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment