Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/840270cc52dbbb412efe9190d089b801 to your computer and use it in GitHub Desktop.
Save FrancoStino/840270cc52dbbb412efe9190d089b801 to your computer and use it in GitHub Desktop.
Insert and remove product automatically after certain quantity counts into cart - Cart - Woocommerce
<?
/*
* Insert and remove product automatically after certain quantity counts into cart
*/
add_action( 'woocommerce_before_calculate_totals', 'add_remove_freebie', 50, 1 );
function add_remove_freebie( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$freebie_id = 5902; // <== HERE set the freebie product ID
$has_others = false;
$quantity = 3; // quantity cart
// Loop through cart items
foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Added Woocommerce compatibility version
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
if( $product_id == $freebie_id ) {
// Freebie is in cart
$freebie_key = $cart_item_key;
} else {
// Other items are in cart
$has_others = true;
}
}
// If freebie product is alone in cart we remove it
if( ! $has_others && isset( $freebie_key ) ){
$cart->remove_cart_item( $freebie_key );
} elseif ( $has_others && ! isset( $freebie_key ) && WC()->cart->get_cart_contents_count() >= $quantity ) {
$cart->add_to_cart($freebie_id);
}
$product_cart_id = WC()->cart->generate_cart_id( $freebie_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart && WC()->cart->get_cart_contents_count() < $quantity ) {
$cart->remove_cart_item( $in_cart );
}
}
/**
* Filters the reported number of cart items.
* Counts only items NOT in certain category.
*
* @param int $count
* @return int
*/
function so_43498002_cart_contents_count( $count ) {
$cart_items = WC()->cart->get_cart();
$subtract = 0;
foreach ( $cart_items as $key => $value ) {
if ( has_term( 'omaggio', 'product_cat', $value['product_id'] ) ) {
$count -= $value[ 'quantity' ];
}
}
return $count;
}
add_filter( 'woocommerce_cart_contents_count', 'so_43498002_cart_contents_count' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment