Skip to content

Instantly share code, notes, and snippets.

@fbmoises
Created November 23, 2017 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbmoises/d780505180f110ab54366a5746f5f7b8 to your computer and use it in GitHub Desktop.
Save fbmoises/d780505180f110ab54366a5746f5f7b8 to your computer and use it in GitHub Desktop.
Limpiar el carrito y dejar sólo el último producto añadido
// Limpiar el carrito y dejar sólo el último producto añadido
add_action( 'woocommerce_before_checkout_form', 'wcfb_allow_only_the_last_product_added' );
function wcfb_allow_only_the_last_product_added() {
if ( WC()->cart->get_cart_contents_count() > 1 ) {
// Coger la key del último producto añadido
$cart_content = WC()->cart->get_cart();
$lastone_key = key( array_slice( $cart_content, -1, 1, TRUE ) );
// Borrar todos los productos excepto el último
foreach ( $cart_content as $key => $product ) {
if( $key != $lastone_key ){
WC()->cart->remove_cart_item( $key );
}
}
}
// Solo permite comprar 1 unidad de este producto
$lastone_product = WC()->cart->get_cart_item( $lastone_key );
if ( $lastone_product[ 'quantity' ] > 1 ) {
WC()->cart->set_quantity( $lastone_key, 1, true );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment