I managed to add a product if a user is the first buyer. But when what I want to achieve is when a user deletes that product, automatically gift or membership product will be deleted. I was using woocommerce_cart_item_removed, but with no luck. Probably I'm missing something but I don't know what. If someone wants to help me, I will be more then thankful
/*
* This function will check if customer has purchased any product.
*/
function monsalo_has_bought() {
$count = 0;
$bought = false;
if(!get_current_user_id()) {
return false;
}
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => array('wc-completed', 'wc-in-progress', 'in-progress') // Only orders with status "completed" & "In Progress"
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
$count++;
}
// return "true" when customer has already one order
if ( $count > 0 ) {
$bought = true;
}
return $bought;
}
add_action( 'woocommerce_add_to_cart', 'add_membership_product_to_cart', 10, 2 );
/*
* Automatically adding the product to the cart.
*/
function add_membership_product_to_cart( $item_key, $product_id ) {
// Get all member plans
$plans = wc_memberships_get_membership_plans();
$free_product_id = 14275; // Product Id of the free product which will get added to cart
if ( !monsalo_has_bought() || !wc_memberships_is_user_active_member( get_current_user_id(), $plan )) {
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
}
}
}
/*
* WITH THIS CODE I'm HAVING THE PROBLEM
*/
add_action( 'woocommerce_cart_item_removed', 'remove_membership_from_cart', 10, 2 );
function remove_membership_from_cart() {
$free_product_id = 14275;
if ( sizeof( WC()->cart->get_cart() ) < 1 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
WC()->cart->remove_cart_item( $free_product_id );
}
}
}
add_action( 'template_redirect', 'remove_membership_from_cart', 10, 2 );
function remove_membership_from_cart() {
$free_product_id = 14275;
if ( sizeof( WC()->cart->get_cart() ) === 1 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
$cartId = WC()->cart->generate_cart_id( $free_product_id );
$cartItemKey = WC()->cart->find_product_in_cart( $cartId );
WC()->cart->remove_cart_item( $cartItemKey );
}
}
}