How To Clear Cart Except The Very Last Added Item?

I'm trying to clear the cart, but i want to keep the last added item.

fn_clear_cart();

function fn_alter_cart_products(&$cart, $leave_items=0) {
  $item_count = count($cart['products']);
  if( $item_count > $leave_items ) {
    $_products = array_reverse($cart['products'], true);
    foreach($_products as $cartid => $item) {
      if( $leave_items > 0 ) {
        $leave_items--;
        continue; // leave this item
      }
      unset($_products[$cart_id]);
    }
    $cart['products'] = array_reverse($_products,true);
  } 
}
function fn_alter_cart_products(&$cart, $leave_items=0) {
  $item_count = count($cart['products']);
  if( $item_count > $leave_items ) {
    $_products = array_reverse($cart['products'], true);
    foreach($_products as $cartid => $item) {
      if( $leave_items > 0 ) {
        $leave_items--;
        continue; // leave this item
      }
      unset($_products[$cart_id]);
    }
    $cart['products'] = array_reverse($_products,true);
  } 
}

I couldn't get this to work bro

How are you calling it and from where?

I don't even know when and how to call it, I tried calling from smarty and controller but it didn't work, how can i call it? Thanks

I can't answer that for you since I don't know under what conditions you want it to act on the cart. You could call it from a checkout post controller, you could call it from one of the hooks in fn_clear_cart(). Without knowing your business logic it's impossible to say.

I can't answer that for you since I don't know under what conditions you want it to act on the cart. You could call it from a checkout post controller, you could call it from one of the hooks in fn_clear_cart(). Without knowing your business logic it's impossible to say.

do i call it like this fn_alter_cart_products(); or just place the code in the controller?

You would call it with the first parameter being the active $cart and the 2nd argument being the number of items you want left in the cart. It sounds like you do not have any development experience. Suggest you contact a developer (maybe me) with the scenario you want to achieve and let them help you implement it.

No, your code is not correct because it's throwing a php error

No, your code is not correct because it's throwing a php error

Given that it was free and stated as untested, suggest you resolve the php error (since you didn't post it).

I'm trying to do this on checkout page, please find a fix, thank you

If you want help with development, please provide your requirements by clicking the get a quote link in my signature.

We have been using this for several weeks now and it seems to be going nicely.

We have been using this for several weeks now and it seems to be going nicely.

Where did you put the code buddy?


how did you get it to work?