• Hi guys, when I add an item to the cart, the following code will check if the item already exists in the cart, if it does, delete the product from the cart and add the item again but with the new quantity.

    add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

    function woo_custom_add_to_cart_before( $cart_item_data ) {
    $cart = WC()->instance()->cart;
    $id = $_POST[‘product_id’];
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
    $cart->set_quantity($cart_item_id,0);
    }
    return true;
    }

    This works fine, but doesn’t allow me to add the item for a second time. For example an item is added using ajax, I then adjust the quantity and click the add to cart button for a second time but nothing happens – the cart is not updated, I have to refresh the page before I can edit the same item again. How can I customise my code to edit the quantity multiple times without the need to refresh? Really would appreciate the help on this as I’ve spent days researching and trying tons of solutions.

    https://www.ads-software.com/plugins/woocommerce/

Viewing 5 replies - 1 through 5 (of 5 total)
  • I probably would need to see the rest of your code, because

    item is added using ajax, I then adjust the quantity and click the add to cart button for a second time but nothing happens

    isn’t the way that WooCommerce behaves by default. From a shop archive you can’t edit the quantity and add that by ajax.

    But modifying some of my old code, here’s something that would make sure a “special item” is removed from the cart before being added.

    /*
    Plugin Name: WooCommerce Special Handling
    Description: Removes certain items from cart before re-adding them
    Version: 1.0
    Author: Kathy Darling
    Author URI: https://kathyisawesome.com
    Requires at least: 4.1.0
    Tested up to: 4.1.0
    
    Copyright: ? 2015 Kathy Darling.
    License: GNU General Public License v3.0
    License URI: https://www.gnu.org/licenses/gpl-3.0.html
    
    */
    
    /**
     * The Main WC_Special_Handling class
     **/
    if ( ! class_exists( 'WC_Special_Handling' ) ) :
    
    class WC_Special_Handling {
    
    	/**
    	 * WC_Special_Handling init
    	 *
    	 * @access public
    	 * @since 1.0
    	 */
    
    	public static function init() { 
    
    		// product meta
    		add_action( 'woocommerce_product_options_general_product_data', array( __CLASS__, 'add_to_wc_metabox' ) );
    		add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'process_wc_meta_box' ), 10, 2 );
    
    		// validation - ensure product is never in the cart with other products
    		add_filter( 'woocommerce_add_to_cart_validation', array( __CLASS__, 'maybe_remove_item' ), 10, 6 );
    
        }
    
    	/*-----------------------------------------------------------------------------------*/
    	/* Product Write Panels */
    	/*-----------------------------------------------------------------------------------*/
    
    	/*
    	* Add text inputs to product metabox
    	* @since 1.0
    	*/
    	public static function add_to_wc_metabox(){
    		global $post;
    
    		echo '<div class="options_group">';
    
    		echo woocommerce_wp_checkbox( array(
    			'id' => '_special_handling',
    			'label' => __( 'Special Handling', 'your-plugin' ) ,
    			'description' => __( 'For special items that need to be removed/re-added to cart.' )
    			)
    		);
    
    		echo '</div>';
    
    	}
    
    	/*
    	 * Save extra meta info
    	 * @since 1.0
    	 */
    	public static function process_wc_meta_box( $post_id, $post ) {
    
    		if ( isset( $_POST['_special_handling'] ) ) {
    			update_post_meta( $post_id, '_special_handling', 'yes' );
    		} else {
    			update_post_meta( $post_id, '_special_handling', 'no' );
    		}
    
    	}
    
    	/*-----------------------------------------------------------------------------------*/
    	/* Check Cart for presence of certain items */
    	/*-----------------------------------------------------------------------------------*/
    
    	/**
    	 * When an item is added to the cart, remove other products
    	 * based on WooCommerce Subscriptions code
    	 */
    	public static function maybe_remove_item( $valid, $product_id, $quantity, $variation_id = null, $variations = array(), $cart_item_data = array() ){
    
    		if ( self::is_item_special( $product_id ) && WC()->cart->get_cart_contents_count() > 0 ){
    
    				$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id );
    
    				// Generate a ID based on product ID, variation ID, variation data, and other cart item data
    				$cart_id        = WC()->cart->generate_cart_id( $product_id, $variation_id, $variations, $cart_item_data );
    
    				// Find the cart item key in the existing cart
    				$cart_item_key  = WC()->cart->find_product_in_cart( $cart_id );
    
    				if( $cart_item_key ){
    					WC()->cart->set_quantity( $cart_item_key, 0 );
    					wc_add_notice(  __( 'Here is some message.', 'your-plugin' ) );
    				}
    
    		} 
    
    		return $valid;
    	}
    
    	/*-----------------------------------------------------------------------------------*/
    	/* Helper methods */
    	/*-----------------------------------------------------------------------------------*/
    
    	/*
    	 * check if an item has custom field
    	 */
    	public static function is_item_special( $product_id ){
    
    		if ( 'yes' == get_post_meta( $product_id, '_special_handling', true ) ){
    			return TRUE;
    		} else {
    			return false;
    		}
    	}
    
    } //end class: do not remove or there will be no more guacamole for you
    
    endif; // end class_exists check
    
    // Launch the whole plugin
    WC_Special_Handling::init();
    Thread Starter lukem15

    (@lukem15)

    Sorry to be such a newbie, but where do I add this code? I’ve added to my function.php but didn’t seem to make any difference.

    Here is a link to all my customised files – Click here. My “shop” is a page with multiple [add_to_cart id=”1193″] shortcodes for around 100+ products. The items are added to the cart via AJAX. Hopefully this info will help.

    Thank you very much for your help!

    Hi Luke,

    My code is meant to be its own plugin. See how to create a plugin. So save the whole block as a php file in the wp-content/plugins folder, ex: wp-content/plugins/woocommerce-special-handling/woocommerce-special-handling.php. And don’t forget an opening <?php which i don’t think showed up in my code block.

    Why do you need so many shortcodes? I’ll let you test the plugin before I try your theme.

    Thread Starter lukem15

    (@lukem15)

    Unfortunately, it didn’t work – no items are removed and the original quantity that was submitted first is added to the total. I think it maybe a problem with AJAX? When I view ?wc-ajax=add_to_cart in developer tools the form data quantity always remains the same value, even tho I’ve inputted a different value and click add to cart.

    The code I posted above did remove the item from the cart, and it added the correct quantity but after the first add the old item quantity was always added (it didn’t change)

    I need so many shortcodes because they’re in table columns

    Well the [add_to_cart id="403"] shortcode doesn’t have a quantity input so it only ever adds 1 item at a time, unless you have modified that somehow.

    I tested this locally and the result is that every time you click ‘add to cart’ the cart drops the old version and adds the new version (but at a quantity of 1) so the cart quantity is pretty much always stuck at 1.

    I will check the theme you are using later.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘I have to refresh the page before I can update item quantity?’ is closed to new replies.