AJAX is fun. Most people prefer AJAX because AJAX allows easier and quicker interaction between the user and website as pages are not reloaded for content to be displayed.

I will explain you step by step how you can add a product to the cart from your single product page with AJAX in WooCommerce. This a lengthy article so make sure you have some coffee with you.

Adding Cart Icon in the header

The first step is to add an icon in the header which will show your cart contents after AJAX updates the cart or show the existing cart contents when the page is loaded.

You can pick any image of a basket/cart or any font-awesome icon to display this. You can also display the cart count, that is the number of products currently in the cart and also show the amount.

Here is the code to show the cart items count and total in the header

<div class="secondary-cart">
	<?php $items = WC()->cart->get_cart();
	global $woocommerce;
	$item_count = $woocommerce->cart->cart_contents_count; ?>
	<a class="cart-totals" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">Cart (<span><?php echo $item_count; ?></span>)</a>
</div>

The icon-basket class can be used to display an icon from font-awesome or if you want, you can use an image there as well.

The cart-count-total class will contain the number of items that the user has in his/her shopping cart.

Add the necessary CSS to those classes the way you want them to look. I have used this on a theme so this is how it looks after adding that code.

woocommerce add to cart AJAX

We also need a drop down here for the cart items to show up so let’s add the drop down div to the code.

<div class="secondary-cart">
	<?php $items = WC()->cart->get_cart();
	global $woocommerce;
	$item_count = $woocommerce->cart->cart_contents_count; ?>
	<a class="cart-totals" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">Cart (<span><?php echo $item_count; ?></span>)</a>
	<div class="cart-dropdown">
		<div class="cart-dropdown-inner">
			<h4>Shopping Bag</h4>
		</div>
	</div>
</div>

We will also want to display the existing cart items here so we use the following code to display that along with the cart and checkout links

<div class="secondary-cart">
	<?php $items = WC()->cart->get_cart();
	global $woocommerce;
	$item_count = $woocommerce->cart->cart_contents_count; ?>
	<a class="cart-totals" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">Cart (<span><?php echo $item_count; ?></span>)</a>
	<div class="cart-dropdown">
		<div class="cart-dropdown-inner">
			<?php if ($items) { ?>
				<h4>Shopping Bag</h4>

				<?php foreach($items as $item => $values) { 
					$_product = $values['data']->post; ?>
					
					<div class="dropdown-cart-wrap">
						<div class="dropdown-cart-left">
							<?php $variation = $values['variation_id'];
	                        if ($variation) {
	                            echo get_the_post_thumbnail( $values['variation_id'], 'thumbnail' ); 
	                        } else {
	                            echo get_the_post_thumbnail( $values['product_id'], 'thumbnail' ); 
	                        } ?>
						</div>

						<div class="dropdown-cart-right">
							<h5><?php echo $_product->post_title; ?></h5>
							<p><strong>Quantity:</strong> <?php echo $values['quantity']; ?></p>
							<?php global $woocommerce;
							$currency = get_woocommerce_currency_symbol();
							$price = get_post_meta( $values['product_id'], '_regular_price', true);
							$sale = get_post_meta( $values['product_id'], '_sale_price', true);
							?>
							 
							<?php if($sale) { ?>
								<p class="price"><strong>Price:</strong> <del><?php echo $currency; echo $price; ?></del> <?php echo $currency; echo $sale; ?></p>
							<?php } elseif($price) { ?>
								<p class="price"><strong>Price:</strong> <?php echo $currency; echo $price; ?></p>    
							<?php } ?>
						</div>

						<div class="clear"></div>
					</div>
				<?php } ?>

				<div class="dropdown-cart-wrap dropdown-cart-subtotal">
					<div class="dropdown-cart-left">
						<h6>Subtotal</h6>
					</div>

					<div class="dropdown-cart-right">
						<h6><?php echo WC()->cart->get_cart_total(); ?></h6>
					</div>

					<div class="clear"></div>
				</div>

				<?php $cart_url = $woocommerce->cart->get_cart_url();
				$checkout_url = $woocommerce->cart->get_checkout_url(); ?>

				<div class="dropdown-cart-wrap dropdown-cart-links">
					<div class="dropdown-cart-left dropdown-cart-link">
						<a href="<?php echo $cart_url; ?>">View Cart</a>
					</div>

					<div class="dropdown-cart-right dropdown-checkout-link">
						<a href="<?php echo $checkout_url; ?>">Checkout</a>
					</div>

					<div class="clear"></div>
				</div>
			<?php } else { ?>
				<h4>Shopping Bag</h4>

				<div class="dropdown-cart-wrap">
					<p>Your cart is empty.</p>
				</div>
			<?php } ?>
		</div>
	</div>
</div>

After adding the above code, add the CSS that you want to add to style this dropdown. This is how the drop down looks on the theme that I am creating this on.

woocommerce add to cart AJAX

Now that the header is ready. Let’s begin the WooCommerce part.

Adding JS to the WooCommerce Add to Cart Button on Single Product page

By default if the user clicks on the add to cart button on the single product pages, that item is added to the cart and then a message is displayed below the header which says that the item has been added to the cart.

So let’s disable that altogether and create our own AJAX for that button

Place the following code in your JS file of your theme. If you don’t have one (which is very unlikely to happen) or if you are using a child theme, use wp_enqueue_script() to add a JS file to your theme. Also use wp_localize_script to get the admin-AJAX.php URL in your AJAX call.

jQuery(document).ready(function() {
	jQuery(".single_add_to_cart_button").click(function(e) {
		e.preventDefault();

		console.log('clicked');	
	});
});

The above code will override the add to cart button on the archive pages to function and just as a test it will show a “clicked” text in the developer console of your browser. You can see the developer console on your browser by pressing the F12 button. After adding the above code, if you head over to any single product page, you will see a message in your console, something like this..

woocommerce add to cart AJAX

Now let’s add the AJAX call to the above JS code

If you just have simple products in your website, then use this code.

jQuery('.single_add_to_cart_button').click(function(e) {
	e.preventDefault();
	jQuery(this).addClass('adding-cart');
	var product_id = jQuery(this).val();
	var quantity = jQuery('input[name="quantity"]').val();
	jQuery('.cart-dropdown-inner').empty();

	jQuery.ajax ({
		url: crispshop_ajax_object.ajax_url,  
		type:'POST',
		data:'action=crispshop_add_cart_single&product_id=' + product_id + '&quantity=' + quantity,

		success:function(results) {
			jQuery('.cart-dropdown-inner').append(results);
			var cartcount = jQuery('.item-count').html();
			jQuery('.cart-totals span').html(cartcount);
			jQuery('.single_add_to_cart_button').removeClass('adding-cart');
			jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
			jQuery('.cart-dropdown').addClass('show-dropdown');
            setTimeout(function () { 
                jQuery('.cart-dropdown').removeClass('show-dropdown');
            }, 3000);
		}
	});
});

If you have simple as well as variable products on your website, then use the following code.

jQuery('.single_add_to_cart_button').click(function(e) {
	e.preventDefault();
	jQuery(this).addClass('adding-cart');
	var product_id = jQuery(this).val();
	var variation_id = jQuery('input[name="variation_id"]').val();
	var quantity = jQuery('input[name="quantity"]').val();
	console.log(quantity);
	jQuery('.cart-dropdown-inner').empty();

	if (variation_id != '') {
		jQuery.ajax ({
			url: crispshop_ajax_object.ajax_url,
			type:'POST',
			data:'action=crispshop_add_cart_single&product_id=' + product_id + '&variation_id=' + variation_id + '&quantity=' + quantity,

			success:function(results) {
				jQuery('.cart-dropdown-inner').append(results);
				var cartcount = jQuery('.item-count').html();
				jQuery('.cart-totals span').html(cartcount);
				jQuery('.single_add_to_cart_button').removeClass('adding-cart');
				jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
				jQuery('.cart-dropdown').addClass('show-dropdown');
                setTimeout(function () { 
                    jQuery('.cart-dropdown').removeClass('show-dropdown');
                }, 3000);
			}
		});
	} else {
		jQuery.ajax ({
			url: crispshop_ajax_object.ajax_url,  
			type:'POST',
			data:'action=crispshop_add_cart_single&product_id=' + product_id + '&quantity=' + quantity,

			success:function(results) {
				jQuery('.cart-dropdown-inner').append(results);
				var cartcount = jQuery('.item-count').html();
				jQuery('.cart-totals span').html(cartcount);
				jQuery('.single_add_to_cart_button').removeClass('adding-cart');
				jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
				jQuery('.cart-dropdown').addClass('show-dropdown');
                setTimeout(function () { 
                    jQuery('.cart-dropdown').removeClass('show-dropdown');
                }, 3000);
			}
		});
	}
});

The product_id will pull in the ID of the product. quantity will get the quantity selected by the user. variation_id gets the variation ID of the item that is added to the cart. We also run a conditional tag on ‘variation_id’ so that we can pass the variation ID to the AJAX function. ‘.empty()’ is used to empty the contents of the drop down so that we can update it with new content. The ‘crispshop_add_cart_single’ is the function which will add the product to the cart and then send back the cart contents to update the drop down in the header.

The success function populates the cart dropdown with the new cart items. It also updates the cart count. In the theme that I created, I had added an animation where the page would scroll up to the cart icon/tab in the header and also display the dropdown for 3 seconds. You can modify this the way you want.

The PHP side

Every theme should have a functions.php file. If you are using a child theme, then use the functions.php of the child theme and paste the following code there.

Here is the code to enqueue the JavaScript files in the theme.

function crispshop_scripts() {
    if (is_singular('product')) {
	    wp_enqueue_script( 'crispshop-single', get_template_directory_uri() . '/js/crispshop-single.js', array('jquery'), '1.0.0', true );
	    wp_localize_script( 'crispshop-single', 'crispshop_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
	}
}
add_action( 'wp_enqueue_scripts', 'crispshop_scripts' );

I have used the conditional tag is_singular() so that the JavaScript file is loaded only on the product pages. wp_localize_script() is used to pass the admin-ajax.php file into the JavaScript function.

The following is the functionality of adding the product to the cart and then passing on the results to the AJAX success function.

function crispshop_add_cart_single_ajax() {
	$product_id = $_POST['product_id'];
	$variation_id = $_POST['variation_id'];
	$quantity = $_POST['quantity'];

	if ($variation_id) {
		WC()->cart->add_to_cart( $product_id, $quantity, $variation_id );
	} else {
		WC()->cart->add_to_cart( $product_id, $quantity);
	}

	$items = WC()->cart->get_cart();
	global $woocommerce;
	$item_count = $woocommerce->cart->cart_contents_count; ?>

	<span class="item-count"><?php echo $item_count; ?></span>

	<h4>Shopping Bag</h4>

	<?php foreach($items as $item => $values) { 
		$_product = $values['data']->post; ?>
		
		<div class="dropdown-cart-wrap">
			<div class="dropdown-cart-left">
				<?php $variation = $values['variation_id'];
                if ($variation) {
                    echo get_the_post_thumbnail( $values['variation_id'], 'thumbnail' ); 
                } else {
                    echo get_the_post_thumbnail( $values['product_id'], 'thumbnail' ); 
                } ?>
			</div>

			<div class="dropdown-cart-right">
				<h5><?php echo $_product->post_title; ?></h5>
				<p><strong>Quantity:</strong> <?php echo $values['quantity']; ?></p>
				<?php global $woocommerce;
				$currency = get_woocommerce_currency_symbol();
				$price = get_post_meta( $values['product_id'], '_regular_price', true);
				$sale = get_post_meta( $values['product_id'], '_sale_price', true);
				?>
				 
				<?php if($sale) { ?>
					<p class="price"><strong>Price:</strong> <del><?php echo $currency; echo $price; ?></del> <?php echo $currency; echo $sale; ?></p>
				<?php } elseif($price) { ?>
					<p class="price"><strong>Price:</strong> <?php echo $currency; echo $price; ?></p>    
				<?php } ?>
			</div>

			<div class="clear"></div>
		</div>
	<?php } ?>

	<div class="dropdown-cart-wrap dropdown-cart-subtotal">
		<div class="dropdown-cart-left">
			<h6>Subtotal</h6>
		</div>

		<div class="dropdown-cart-right">
			<h6><?php echo WC()->cart->get_cart_total(); ?></h6>
		</div>

		<div class="clear"></div>
	</div>

	<?php $cart_url = $woocommerce->cart->get_cart_url();
	$checkout_url = $woocommerce->cart->get_checkout_url(); ?>

	<div class="dropdown-cart-wrap dropdown-cart-links">
		<div class="dropdown-cart-left dropdown-cart-link">
			<a href="<?php echo $cart_url; ?>">View Cart</a>
		</div>

		<div class="dropdown-cart-right dropdown-checkout-link">
			<a href="<?php echo $checkout_url; ?>">Checkout</a>
		</div>

		<div class="clear"></div>
	</div>

	<?php die();
}

add_action('wp_ajax_crispshop_add_cart_single', 'crispshop_add_cart_single_ajax');
add_action('wp_ajax_nopriv_crispshop_add_cart_single', 'crispshop_add_cart_single_ajax');

We fire the ‘crispshop_add_cart_single’ function in the functions.php file which first pulls the item which was sent to it from the AJAX function. We then add the product to the cart along with the quantity and the variation which was added. Then we use the WC()->cart->get_cart() function to get the items in the cart and then create the HTML markup for the cart drop down. The above function will return the product image, title, quantity and the price of the products in the cart. In addition to that, it will also show the Subtotal (since total price is calculated after entering the shipping details) and the WooCommerce cart and checkout page links.

This is how my cart drop down looks after I added the CSS for that particular site.

woocommerce add to cart AJAX

You can view a demo of the above code at CrispShop which is a Free WooCommerce Theme

You can view our website at CrispThemes, where you can download Free WordPress Themes and Plugins

Feel free to comment or ask anything you want.

Share on facebook Tweet this Article Mail this Article

61 thoughts on “WooCommerce Add to Cart with Ajax on Single Product Page

  1. hi. thanks for your shared. Do you have WooCommerce Add to Cart with Ajax on Single Product Page Demo?

  2. Is it possible to share which page the codes should be added to? Being new to wordpress/woocommerce, the file structure is still a confusing mess to me so some help with that will be most appreciated!

  3. Hey! Great tutorial – exactly what I’ve been looking for!

    When I add the code to the project I’m working on, I’m getting this issue however: “Notice: post was called incorrectly. Product properties should not be accessed directly.”

    It appears to be on line 15 the issue is. I’m trying to solve it currently, but as I’m new to WooCommerce development I have no idea how to work around this issue 🙂 Just thought I’d give you a heads up!

    Cheers

    1. Hello Nadal,

      Thanks for reading the tutorial. I just tried the above code in a fresh install with the 20seventeen theme and I didn’t come across any error at all? Can you try it on a 2017 or 16 theme and see if the error is not there.

      Also WooCommerce updated their code a bit, so I have modified the code a little bit.

      You can see a demo of it as well here on a custom theme.

      http://crispshop.crispthemes.com/product/ninja-silhouette-2/

  4. Hey, big help as I was trying to figure this out but I’m getting:

    my_ajax_object is not defined at HTMLButtonElement.ajaxAdd

    ..any ideas? TIA.

      1. Yeah that was issue :). Doesn’t work for me though as I’m using Woocommerce Deposits and Woocommerce Easy Bookings which screw with the values and have their own script etc. Guess I’ll have to dig through in my own time. Thanks for a great tutorial though.

        1. Hello,

          Replace JS_DIR_URI with get_stylesheet_directory_uri(), so that code should look like this.

          wp_enqueue_script( ‘frontend-ajax’, get_stylesheet_directory_uri() . ‘/frontend-ajax.js’, array(‘jquery’), null, true );

          If your JS files are in a folder then specify a folder as well.

          wp_enqueue_script( ‘frontend-ajax’, get_stylesheet_directory_uri() . ‘/foldername/frontend-ajax.js’, array(‘jquery’), null, true );

  5. Great snippet! Works like a charm. Only one thing, if you empty your cart the products remain in the cart icon dropdown.
    Maybe you know why?

    Thanks again!
    Luke

    1. Hello Luke,

      Thanks for your comment. For your question, are you doing that in the cart page?

      If yes, then I have not added the Ajax for that. I would usually hide that dropdown from the cart page since they are on the cart page itself, so they can see the products in their cart.

      However if you want that to work as well, you will have to use the action hook “woocommerce_cart_item_removed” to remove that item from the dropdown.

      Regards,
      Patrick.

      1. Thanks for the solution! Totally makes sense.

        One little thing I was curious about, when we add a variation to the cart, the variation thumbnail image shows the default thumb, not the chosen variation thumb.

        Check it out here https://staging.clevercreative.com/product/bugaboo-stroller/

        Pick a variation color and add it to the cart, you’ll see it show the yellow stroller and not your chosen color.

        Thanks for your help! Love what you’ve made 🙂
        Luke

        1. Hi Luke,

          Thanks for pointing this out. I didn’t think of the variation image while writing this code.

          Replace..

          <?php echo get_the_post_thumbnail( $values['product_id'], 'thumbnail' ); ?>

          with…

          <!-- Checks whether the product is a variation, then display the variation image. -->
          <?php $variation = $values['variation_id'];
          if ($variation) {
          	echo get_the_post_thumbnail( $values['variation_id'], 'thumbnail' ); 
          } else {
          	echo get_the_post_thumbnail( $values['product_id'], 'thumbnail' ); 
          } ?>

          I have updated the code in the article above as well.

          Regards,
          Patrick.

          1. Wonderful Patrick! Works great.

            Thanks a million for your expertise 🙂

            Look for the site coming soon!

            Take care,
            Luke

  6. Amazing tutorial. Can you create a tutorial like this to ajax refresh and add to cart on the archive product page?

    1. Thanks. The archive pages already have AJAX add to cart functionality, however they just show a checkbox with a “Added to Cart” or similar message, that’s why I didn’t thought it would be needed.

      However, I will create one and post it on this website 🙂

  7. There is a issue here and i suggest you include the

    The code displayed here is wronge https://developer.wordpress.org/reference/functions/wp_localize_script/#comment-1391

    It states:
    ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),

    your code uses “ajax_url” so correct would be
    ‘ajax_url’ => admin_url( ‘admin-ajax.php’ ),

    Correct and working one
    function theme_enqueue_scripts() {
    /**
    * frontend ajax requests.
    */
    wp_enqueue_script( ‘frontend-ajax’, get_stylesheet_directory_uri() . ‘/frontend-ajax.js’, array(‘jquery’), null, true );
    wp_localize_script( ‘frontend-ajax’, ‘my_ajax_object’,
    array(
    ‘ajax_url’ => admin_url( ‘admin-ajax.php’ )
    )
    );
    }
    add_action( ‘wp_enqueue_scripts’, ‘theme_enqueue_scripts’ );

    Happy hacking
    https://twitter.com/mathiiias123

    1. Hi Mathias,

      Thanks for pointing that out. A lot of people were facing errors in that code. So I updated the entire code above and included the wp_localize_script() code as well 🙂

      Patrick.

  8. Hi Patrik,

    I am getting this error:
    app.js?ver=4.8.1:12 Uncaught ReferenceError: my_ajax_object is not defined

    It looks like ‘wp_localize_script’ not working for me. How do I get “admin-AJAX.php” file?
    This is how I added ‘wp_localize_script’:

    wp_localize_script( ‘ajax-js’, ‘my_ajax_object’,
    array(
    ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
    )
    );

    I am using “Divi” plugin and customising it by adding this plugin from themes folder. My ‘js’ folder path is:

    themes/my-divi-theme/js/app.js

    Please guide me how to fix this error.

    Thanks

    1. Hi I have figured where I been making the mistake and somehow made the whole thing working.

      Can we make some custom changes in here?

      1. My website have multiple products details (single-product) at a single page and so “Add to Cart” button. So when ever I click on “Add to Cart” it to not update the item count at the header.

      2. I have shown products variation and its required to show on the cart page. Its working with WooCommerce default “Add to cart” but not working after using this code. So I would like to know how can I achieve it in cart as well as “Cart over view” dropdown on the header.

      3. After adding 1 product in cart, it do not allow to add more product of same variation. Website show error “You cannot add in cart” but error show at the top of the page in “single product summary” -> error but I want to show errors right above the button I am clicking.

      4. Show loading if ajax is taking too much time.

      Thanks.

      1. Hi iVipera,

        1. I have updated the code above. The previous one did not include the header cart count update. So please take a look at the updated code above. 🙂

        2. Do you mean the variation is not added to the cart? Or the variation “type” is not displaying?

        3. Hm. Never heard of this. I just added same products in the cart, and all it did was increase the quantity of the cart and the amount. Are you using any other plugin which controls the cart or woocommerce?

        4. In the updated code above, I have included the classes for loaders and also included timeouts, etc. You can take a look at this theme and see how I have added the loaders. https://www.crispthemes.com/crispshop-free-responsive-woocommerce-theme/

        Thanks !

        Patrick.

  9. Thanks for the great article. Strange thing is happening to me and wondered if you could help/any ideas.

    When I add to cart, it updates the .cart-dropdown-inner with the whole website page rather than the cart results.

    It seems as though there is an issue with the ajax results.

    Any ideas?

      1. Hello Peter,

        I have updated the code a bit, I had not included the cart count change in the earlier code. Please take a look at the updated code and see if everything is working good. 🙂

        Patrick.

  10. i’m using a divi theme, i tried to put itthe very first part of your code to my header.php the cart icon is not showing

    1. Hello Joseph,

      I am not sure about the DIVI theme, but if you can create a child theme and look at DIVI docs to see how you can add custom content to the header, then you can make it work am sure.

      DIVI isn’t a free theme so you will have to contact their support for any kind of documentation or support.

      Good luck !

      Patrick

  11. Hey Patrick, thanks for taking the time to put this together, really useful!

    I’ve managed to get everything working, except the store I’m using it on has a small inventory and there’s a high risk of exceeding the stock level when adding to cart. Unless I’ve missed something it seems to only output the error message when refreshing the product page, not in the cart modal.

    Is there a way you know of to output these messages (which are seemingly being triggered by woocommerce already) or do I need to manually check stock in the crispshop_add_cart_single_ajax function?

    I’ve tracked down the standard wc_print_notices() function but it only outputs in crispshop_add_cart_single_ajax if I manually add a notice before it – i.e. wc_add_notice( ‘This is an error notice’, ‘error’ );

    Any ideas appreciated!

    Thanks!

    1. Hello Ash,

      For a better user experience, I guess it would be better to just hide the “Add to Cart” button if the product is out of stock and display a “Out of Stock” message, since there would be no point in the user clicking the button if the product is not in stock.

      However, if you want to display it after clicking that button, you can use the conditional tag is_in_stock(). You will have to use this in the crispshop_add_cart_single_ajax function.

      Here is the documentation for that.

      https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html#_is_in_stock

      You can see an example here as well.

      https://stackoverflow.com/questions/41148592/woocommerce-check-stock-of-product-id-before-adding

      Hope this helps. Good Luck.

      Patrick.

  12. Hello again Patrick, I had a quick question, is there any way we can embed product taxonomy in the html? I more or less need to run some scripts or css to hide sub items in a product bundle (from the Product Bundle plugin).

    If you want to see, add this product to your cart (http://stage.lileo.co/product/premium-package-for-newborns/) and hover over the header cart icon. You see the top “Premium Package…”? We want to keep that, but remove all the bundle sub items. I can work with whatever you give me.

    Hope that makes sense 🙂
    Appreciate your support!
    Luke

    1. Hello Luke,

      I tried to add that product to the cart but it’s out of stock 😀

      Let me know when you have fixed that and then I will try again.

      Patrick.

      1. Oh! Sorry, Patrick, the site was pushed to our main domain (lileo.jp). It is set to maintenance mode. If you wouldn’t mind to send me a quick email (to the email I have with this message), I will reply to your email with login credentials to check it out.

        Thanks so much!
        Luke

        1. Hi Partrick, we have set up a staging site for testing.

          You can add this product to your cart (https://stage.lileo.jp/product/launch-package/), then check the nav icon (from your code).

          You’ll see how all the bundled products are listed. We are looking to only show the bundled main image, not the products in the bundle. So we would need some product info embedded in as a class to reference it for styling. Is that something we could do?

          Thanks for your help!
          Luke

          1. Hi Luke,

            I looked at it now and get what you mean. I think you want to hide the products within the bundle and display just the bundled product name and cost.

            For this, I guess you will have to dig into the code of the plugin and check out what they have done to do the same as above in the cart page. I am sure they will have a conditional tag for that or maybe contact their support since I cannot provide support on premium plugins.

            Good Luck,
            Patrick.

  13. Hi Patrick
    Thank you so much for this tutorial. It was exactly what I was looking for!
    A minor thing you might wanna edit in the code examples with the AJAX request:
    Some of the examples use the “results” variable in the console.log and output function, however I think you mean the “data” variable received from the AJAX request.

    Henrik

  14. Hi
    this is a great tutorial and i used it in my project.
    here is my problem:
    I want to use this tuto in shop page
    is there any solution?

  15. The quantity in the shopping cart is not correct. It shows the number of types of items instead of total number of items.

    1. Hello Peiyi,

      Thanks for pointing that out! I have fixed the code.

      Just replace the following everywhere

      $item_count = count($items);

      with

      global $woocommerce;
      $item_count = $woocommerce->cart->cart_contents_count;

      Regards,
      Patrick.

  16. hi

    i got some troubles with this amazing code. The quantity are good but there is no error message if i want to add more than quantity product in my cart.

    i explain : i got a product with 4 quantity, i already added 4 products in my cart, i try to add another one and even if nothing is added, my cart is showing and i don’t have the woocommerce error message to say i added the most possible quantity to cart.

    i need to reload the product page to show the message, but it will be amazing to not showing the cart and disable the add to card

    Sorry i’m french.. sorry for my english

    1. Hi def, Thanks for pointing this out. I will work on it and update the code to check the quantity as well, as and when I get time.

  17. Hi,
    I wanted to thank you for your simple and complete tutorial of this article.
    The only objection to your codes was related to the fourth line of the jQuery script that:

    var product_id = jQuery(this).val();

    Should be removed with the following code:

    var product_id = jQuery(‘input[name=”add-to-cart”]’).val();

    Thanks

    1. Hello, WooCommerce by default creates the add to cart as a button and not an input field. This might depend on the theme that you are using. Some themes create a custom add to cart area, where they might replace the button with an input element.

  18. Hi, i want to add a bundle product to the cart via AJAX, i have an issue when i add the product this just show the bundle product but not the products than this one have on it. How can i make the cart show the subproducts?

    Thanks for help

    1. Hello Jonathan,

      Sorry I have not made this to work with bundled products add-on. I will work on it and update the code as and when I get time.

      Patrick.

  19. Hello there. Quick question, so I’m building a website on my own using paid theme. I’m just wondering if I can implement this ajax add to cart to my theme? The theme already have the dropdown cart but not on hover, which mean i have to click it then the dropdown appears. Even when I added a product, the page refreshes and the dropdown wouldn’t appear unless I clicked the cart icon. So can I implement this to my website so that the dropdown appears after i add product into cart?

    Thank you in advance!

    1. Hello,

      You can implement this on any theme. You will have to create a custom cart dropdown like I have created and not use the one provided by the theme.

      You can hide the theme’s cart header with css and use the code I provided above.

      Patrick.

  20. Hi! Nice tutorial 🙂

    I have some troubles with variable products. The variable products price and the thumbnail are not working? Also the normal product prices in the cart does not have taxes in it. I got the total price right by changing “price_total” to this “WC()->cart->get_cart_subtotal();” Can you help me with these problems?

    Thanks for the help!

  21. Hello thanks for the great tutorial but I have one question, after adding a product to the cart everything works well but after I delete product the cart dropdown is not updated it should be empty but it still populated.
    Any work arround for that ?
    Thanks

    1. Add this code and you’ll have the possibility to remove the product from your cart

      <?php echo apply_filters('woocommerce_cart_item_remove_link', sprintf('ב, esc_url(WC()->cart->get_remove_url($item)), __(‘Remove this item’, ‘evolve’)), $item); ?>

    2. But if i delete the product directly from the cart page i have to refresh the page to see that the cart dropdown is empty, i would like to use ajax to auto empty the cart dropdown after deleting product from the cart page

  22. Exactly what I am looking for! Thank you for sharing.

    Product adds to the mini cart without loading the page, except there are some notices and deprecated functions which can be easily fixed.

    The main issue I am trying to tackle is how to make the pricing rules of the plugin I use to show. As it is, it adds the original prices before the pricing rules.

    Could you give me a pointer to where I should be looking at?

    The plugin in question is https://codecanyon.net/item/woocommerce-dynamic-pricing-discounts/7119279

    Best Regards,
    Nick.

  23. Hi Partrickk,

    you tutorial is awesome, i read single and archive add cart ajax tutorials.

    i have a question…

    In case of Variable Product, the cart doesn’t show the price… it only shows quantity….

    so how could i resolve that.?

    Means in case of variable product… with quantity i also want to show the price!

    I checked for this variable product: http://crispshop.crispthemes.com/product/ship-your-idea-2/

    In cart it shows only quantity… no Price Tag!

    So please help me!

  24. After Woocommerce 2019 update, ajax cart count is not working. when a product added to cart, it counter doesn’t change. after refresh page it shows properly. how can i make it right?

Leave a Reply

Your email address will not be published. Required fields are marked *