WooCommerce 3.3.X版本购物车单商品限制代码适配咨询
Fix: Allow Only One Item in WooCommerce 3.3.X Cart (Auto-Remove Old Items)
Hey there! Let's get this sorted for your WooCommerce 3.3.X setup. The issue with your original code is likely using deprecated hooks or outdated cart methods that don't play nice with 3.X versions. Here's a tested, compatible solution:
Option 1: Empty Cart Before Adding New Item (Simplest Approach)
This method clears the cart right before adding the new item, ensuring only the latest product stays in the cart:
add_action( 'woocommerce_before_add_to_cart_action', 'empty_cart_before_new_item' ); function empty_cart_before_new_item() { // Get the WooCommerce cart object $cart = WC()->cart; // Only empty if cart isn't already empty if ( ! $cart->is_empty() ) { $cart->empty_cart(); // Optional: Add a user notice to explain the change wc_add_notice( __( 'We’ve removed previous items from your cart—only the product you just added is kept.', 'woocommerce' ), 'notice' ); } }
Option 2: Keep Only the Newly Added Item (Preserve Cart State Briefly)
If you want to remove all items except the one just added (useful if you need to run checks before removing), use this:
add_action( 'woocommerce_add_to_cart', 'keep_only_latest_cart_item', 10, 6 ); function keep_only_latest_cart_item( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) { $cart = WC()->cart; // If cart has more than one item after adding the new one if ( count( $cart->get_cart() ) > 1 ) { // Loop through all cart items foreach ( $cart->get_cart() as $key => $item ) { // Skip the newly added item if ( $key !== $cart_item_key ) { // Remove the old item $cart->remove_cart_item( $key ); } } wc_add_notice( __( 'Your cart has been updated to only include the latest product you added.', 'woocommerce' ), 'notice' ); } }
Why This Works for WooCommerce 3.3.X
- Uses WC 3.X-compatible hooks:
woocommerce_before_add_to_cart_actionandwoocommerce_add_to_cartare both fully supported in 3.3.X. - Relies on official cart methods:
empty_cart()andremove_cart_item()are the correct, non-deprecated ways to modify the cart in this version. - Avoids outdated functions like
get_cart_contents()(replaced byget_cart()) or old validation hooks that no longer trigger correctly.
How to Implement
- Copy the code of your chosen option.
- Paste it into your active theme's
functions.phpfile (Appearance > Theme Editor > functions.php) or a custom plugin file. - Save changes and test adding multiple products to your cart—only the latest one should remain.
内容的提问来源于stack exchange,提问作者Dr.MTR
相关产品推荐
相关产品推荐

