View Categories

Ajax add to cart

11 min read

Obratite paznju da na dugme za add to cart dodate klasu single_add_to_cart_button

header.php #

Dodajte ispod hedera ovaj kod kako biste pozvali minicart.

<?php if (! is_checkout()) : ?>
				<div class="mini-cart-wrapper widget_shopping_cart_content">
					<?php woocommerce_mini_cart(); ?>
				</div>
			<?php endif; ?>

Ukoliko imate quantity broj pored ikonice u hederu dodati ikonicu u ovom kodu odnosno pored cart-count.

<li class="flex header-bag">
							<a href="#" class="flex" id="cart-trigger">
								
								<span class="cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>

							</a>
						</li>

ajax-add-to-cart.js #

jQuery(document).ready(function ($) {
  // Handle add to cart
  $("#cart-trigger").on("click", function (e) {
    e.preventDefault();

    $(".mini-cart-holder").css("transform", "translateX(0)");
    $(".site-overlay").addClass("site-overlay--active");
  });
  $(".site-overlay").on("click", function () {
    $(".mini-cart-holder").css("transform", "translateX(100%)");
    $(".site-overlay").removeClass("site-overlay--active");
  });
  $("#close-minicart").on("click", function () {
    $(".mini-cart-holder").css("transform", "translateX(100%)");
    $(".site-overlay").removeClass("site-overlay--active");
  });
  $(".single_add_to_cart_button").on("click", function (e) {
    e.preventDefault();

    var $thisbutton = $(this),
      $form = $thisbutton.closest("form.cart"),
      product_qty = 1,
      product_id = $thisbutton.attr("value"),
      variation_id = 0;

    if ($form.length) {
      product_qty = $form.find("input[name=quantity]").val() || 1;
      product_id = $form.find("input[name=product_id]").val() || product_id;
      variation_id = $form.find("input[name=variation_id]").val() || 0;
    }

    var data = {
      action: "ql_woocommerce_ajax_add_to_cart",
      product_id: product_id,
      product_sku: "",
      quantity: product_qty,
      variation_id: variation_id,
    };

    $.ajax({
      type: "post",
      url: wc_add_to_cart_params.ajax_url,
      data: data,
      beforeSend: function () {
        $thisbutton.removeClass("added").addClass("loading");
      },
      complete: function () {
        $thisbutton.addClass("added").removeClass("loading");
      },
      success: function (response) {
        if (response.error && response.product_url) {
          window.location = response.product_url;
          return;
        } else {
          $(document.body).trigger("added_to_cart", [
            response.fragments,
            response.cart_hash,
            $thisbutton,
          ]);
          updateCartCount();

          // Update cart count
          $(".mini-cart-holder").css("transform", "translateX(0)");
          $(".site-overlay").addClass("site-overlay--active");
          // Refresh WooCommerce mini cart
          refreshMiniCart();
        }
      },
    });
  });

  // Handle remove from cart
  $(document).on("click", ".remove_from_cart_button", function (e) {
    e.preventDefault();

    var $thisbutton = $(this),
      cart_item_key = $thisbutton.data("cart_item_key"); // Assuming `data-cart_item_key` attribute holds the key

    var data = {
      action: "ql_woocommerce_ajax_remove_from_cart",
      cart_item_key: cart_item_key,
    };

    $.ajax({
      type: "post",
      url: wc_add_to_cart_params.ajax_url,
      data: data,
      success: function (response) {
        if (response.success) {
          // Update cart count
          updateCartCount();
          $(".mini-cart-holder").css("transform", "translateX(0)");
          // Refresh WooCommerce mini cart
          refreshMiniCart();
        }
      },
    });
  });

  // Update cart count function
  function updateCartCount() {
    $.ajax({
      type: "post",
      url: wc_add_to_cart_params.ajax_url,
      data: {
        action: "ql_update_cart_count",
      },
      success: function (response) {
        if (response.success) {
          $("span.cart-count").text(response.data.cart_count);
        }
      },
    });
  }

  // Function to refresh WooCommerce mini cart

  function refreshMiniCart() {
    $.ajax({
      url: wc_add_to_cart_params.wc_ajax_url
        .toString()
        .replace("%%endpoint%%", "get_refreshed_fragments"),
      type: "POST",
      success: function (response) {
        if (response && response.fragments) {
          $.each(response.fragments, function (key, value) {
            $(key).replaceWith(value);
          });

          $(document.body).trigger("wc_fragments_refreshed");
        }
      },
    });
  }
});

functions.php #


function ql_woocommerce_ajax_add_to_cart_js()
{
	wp_enqueue_script('custom_script-ajax', get_template_directory_uri() . '/assets/js/ajax-add-to-cart.js', array(), _S_VERSION, true);

}
add_action('wp_enqueue_scripts', 'ql_woocommerce_ajax_add_to_cart_js');

add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');

function ql_woocommerce_ajax_add_to_cart()
{
	$product_id = apply_filters('ql_woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
	$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
	$variation_id = absint($_POST['variation_id']);
	$passed_validation = apply_filters('ql_woocommerce_add_to_cart_validation', true, $product_id, $quantity);
	$product_status = get_post_status($product_id);
	if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
		do_action('ql_woocommerce_ajax_added_to_cart', $product_id);
		if ('yes' === get_option('ql_woocommerce_cart_redirect_after_add')) {
			wc_add_to_cart_message(array($product_id => $quantity), true);
		}
		WC_AJAX::get_refreshed_fragments();
	} else {
		$data = array(
			'error' => true,
			'product_url' => apply_filters('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
		);
		echo wp_send_json($data);
	}
	wp_die();
}
add_action('wp_ajax_ql_update_cart_count', 'ql_update_cart_count');
add_action('wp_ajax_nopriv_ql_update_cart_count', 'ql_update_cart_count');

function ql_update_cart_count()
{
	$cart_count = WC()->cart->get_cart_contents_count();
	wp_send_json_success(array('cart_count' => $cart_count));
}
add_action('wp_ajax_ql_woocommerce_ajax_remove_from_cart', 'ql_woocommerce_ajax_remove_from_cart');
add_action('wp_ajax_nopriv_ql_woocommerce_ajax_remove_from_cart', 'ql_woocommerce_ajax_remove_from_cart');

function ql_woocommerce_ajax_remove_from_cart()
{
	$cart_item_key = sanitize_text_field($_POST['cart_item_key']);
	WC()->cart->remove_cart_item($cart_item_key);
	WC()->cart->calculate_totals();

	wp_send_json_success();
}

// AJAX QUANTITY IN MINI CART
add_action('wp_ajax_update_cart_item_quantity', 'update_cart_item_quantity');
add_action('wp_ajax_nopriv_update_cart_item_quantity', 'update_cart_item_quantity');

function update_cart_item_quantity()
{
	// Check if the required parameters are set
	if (!isset($_POST['cart_item_key']) || !isset($_POST['quantity'])) {
		wp_send_json_error(['message' => 'Invalid request. Missing parameters.']);
		return;
	}

	// Sanitize and validate parameters
	$cart_item_key = sanitize_text_field($_POST['cart_item_key']);
	$quantity = intval($_POST['quantity']);

	// Check if cart item key and quantity are valid
	if (empty($cart_item_key) || $quantity <= 0) {
		wp_send_json_error(['message' => 'Invalid cart item or quantity.']);
		return;
	}

	// Update the cart quantity
	$cart = WC()->cart;
	if ($cart && $cart->get_cart_item($cart_item_key)) {
		$cart->set_quantity($cart_item_key, $quantity);
		// $cart->calculate_shipping();
		$cart->calculate_totals();
		wp_send_json_success();
	} else {
		wp_send_json_error(['message' => 'Cart item not found.']);
	}
}
function display_short_description_after_add_to_cart()
{
	global $product;

	$short_description = $product->get_short_description();

	if ($short_description) {
		echo '<div class="short-description-after-cart"><span>Materials:</span>';
		echo wp_kses_post($short_description);
		echo '</div>';
	}
}

// Dodajte funkciju nakon dugmeta 'Add to Cart'
add_action('woocommerce_after_add_to_cart_button', 'display_short_description_after_add_to_cart', 20);

mini-cart.php (preurediti po zelji) #

Mini cart sadrzi quantity plus i minus putem ajax-a


<?php if (! WC()->cart->is_empty()) : ?>

	<ul class="woocommerce-mini-cart cart_list product_list_widget <?php echo esc_attr($args['list_class']); ?>">
		<?php
		do_action('woocommerce_before_mini_cart_contents');

		foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
			$_product   = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
			$product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key);

			if ($_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters('woocommerce_widget_cart_item_visible', true, $cart_item, $cart_item_key)) {
				/**
				 * This filter is documented in woocommerce/templates/cart/cart.php.
				 *
				 * @since 2.1.0
				 */
				$product_name      = apply_filters('woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key);
				$thumbnail         = apply_filters('woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key);
				$product_price     = apply_filters('woocommerce_cart_item_price', WC()->cart->get_product_price($_product), $cart_item, $cart_item_key);
				$product_permalink = apply_filters('woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink($cart_item) : '', $cart_item, $cart_item_key);
				$remove_icon_url = esc_url(get_template_directory_uri() . '/assets/icons/removefrommini.svg');
		?>
				<li class="woocommerce-mini-cart-item <?php echo esc_attr(apply_filters('woocommerce_mini_cart_item_class', 'mini_cart_item', $cart_item, $cart_item_key)); ?>">
					<div class="flex justify-between">
						<div class="flex ">

							<?php if (empty($product_permalink)) : ?>
								<?php echo $thumbnail . wp_kses_post($product_name); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
								?>
							<?php else : ?>
								<a class="flex" href="<?php echo esc_url($product_permalink); ?>">
									<div class="product-thumbnail">
										<?php echo $thumbnail;
										?>
									</div>

								</a>

							<?php endif; ?>
							<?php echo wc_get_formatted_cart_item_data($cart_item); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
							?>
							<div class="flex flex-col justify-between pl-18">

								<div class="product-title">
									<?php echo wp_kses_post($product_name);
									?>
								</div>
								<div class="quantity-controls">
									<button class="quantity-minus" data-cart-item-key="<?php echo esc_attr($cart_item_key); ?>">-</button>
									<input type="number" class="quantity-input" value="<?php echo esc_attr($cart_item['quantity']); ?>" readonly />
									<button class="quantity-plus" data-cart-item-key="<?php echo esc_attr($cart_item_key); ?>">+</button>
								</div>

							</div>


						</div>
						<div class="mini-cart-right">
							<div class="flex flex-col justify-between">
								<div class="mini-cart-right-remove">
									<?php
									echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
										'woocommerce_cart_item_remove_link',
										sprintf(
											'<a href="%s" class="remove remove_from_cart_button" aria-label="%s" data-product_id="%s" data-cart_item_key="%s" data-product_sku="%s"><svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 48 48" width="48px" height="48px"><path fill="#F44336" d="M21.5 4.5H26.501V43.5H21.5z" transform="rotate(45.001 24 24)"/><path fill="#F44336" d="M21.5 4.5H26.5V43.501H21.5z" transform="rotate(135.008 24 24)"/></svg></a>',
											esc_url(wc_get_cart_remove_url($cart_item_key)),
											/* translators: %s is the product name */
											esc_attr(sprintf(__('Remove %s from cart', 'woocommerce'), wp_strip_all_tags($product_name))),
											esc_attr($product_id),
											esc_attr($cart_item_key),
											esc_attr($_product->get_sku())
										),
										$cart_item_key
									);
									?>
								</div>
								<div class="mini-cart-right-price">

									<?php echo apply_filters('woocommerce_widget_cart_item_quantity', '<span class="quantity">' . sprintf($product_price) . '</span>', $cart_item, $cart_item_key); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
									?>
								</div>
							</div>


						</div>
					</div>
				</li>
		<?php
			}
		}

		do_action('woocommerce_mini_cart_contents');
		?>
	</ul>

	<div class="mini-cart-footer">
		<?php // if (! is_checkout()) : 
		?>
		<p class="woocommerce-mini-cart__total mini-cart-shipping total not-checkout">
			<strong>Shipping</strong>
			<span>Calculated at next step</span>
		</p>
		<p class="woocommerce-mini-cart__total total not-checkout subtotal-mini">
			<?php
			/**
			 * Hook: woocommerce_widget_shopping_cart_total.
			 *
			 * @hooked woocommerce_widget_shopping_cart_subtotal - 10
			 */
			do_action('woocommerce_widget_shopping_cart_total');
			?>
		</p>
		<?php // else : 
		?>
		<p class="woocommerce-mini-cart__total mini-cart-shipping total is-checkout">
			<strong>Shipping</strong>
			<span><?php echo WC()->cart->get_shipping_total(); ?></span>
		</p>
		<p class="woocommerce-mini-cart__total total is-checkout">
			<strong>Total</strong>
			<span><?php echo WC()->cart->get_total(); ?></span>
		</p>
		<?php // endif; 
		?>
		<?php do_action('woocommerce_widget_shopping_cart_before_buttons'); ?>
		<?php // if (! is_checkout()) : 
		?>

		<p class="woocommerce-mini-cart__buttons buttons not-checkout"><?php do_action('woocommerce_widget_shopping_cart_buttons'); ?></p>
		<?php // else : 
		?>

		<?php // endif; 
		?>
		<?php do_action('woocommerce_widget_shopping_cart_after_buttons'); ?>
	</div>


<?php else : ?>

	<p class="woocommerce-mini-cart__empty-message"><?php esc_html_e('No products in the cart.', 'woocommerce'); ?></p>

<?php endif; ?>
<script>
	jQuery(document).ready(function($) {
		$('.quantity-controls').each(function() {
			var $quantityInput = $(this).find('input.quantity-input');
			var $minusButton = $(this).find('.quantity-minus');
			var $plusButton = $(this).find('.quantity-plus');
			var cartItemKey = $minusButton.data('cart-item-key');

			if (!cartItemKey) {
				console.error('Cart item key is not set.');
				return;
			}

			$minusButton.on('click', function() {
				var quantity = parseInt($quantityInput.val(), 10);
				if (quantity > 1) {
					$quantityInput.val(quantity - 1);
					updateQuantity(cartItemKey, $quantityInput.val());
				}
			});

			$plusButton.on('click', function() {
				var quantity = parseInt($quantityInput.val(), 10);
				$quantityInput.val(quantity + 1);
				updateQuantity(cartItemKey, $quantityInput.val());
			});

			function updateQuantity(cartItemKey, newQuantity) {
				// console.log('Sending AJAX request with:', {
				// 	action: 'update_cart_item_quantity',
				// 	cart_item_key: cartItemKey,
				// 	quantity: newQuantity
				// });

				function updateCartCount() {
					$.ajax({
						type: "post",
						url: wc_add_to_cart_params.ajax_url,
						data: {
							action: "ql_update_cart_count",
						},
						success: function(response) {
							if (response.success) {
								$("span.cart-count").text(response.data.cart_count);
							}
						},
					});
				}

				function refreshMiniCart() {
					$.ajax({
						url: wc_add_to_cart_params.wc_ajax_url
							.toString()
							.replace("%%endpoint%%", "get_refreshed_fragments"),
						type: "POST",
						success: function(response) {
							console.log(response);
							if (response && response.fragments) {
								$.each(response.fragments, function(key, value) {
									$(key).replaceWith(value);
								});

								$(document.body).trigger("wc_fragments_refreshed");
							}
						},
					});
				}
				$.ajax({
					url: '<?php echo admin_url('admin-ajax.php'); ?>',
					type: 'POST',
					data: {
						action: 'update_cart_item_quantity',
						cart_item_key: cartItemKey,
						quantity: newQuantity
					},
					success: function(response) {
						console.log('Response:', response);
						refreshMiniCart();
						updateCartCount();
						if (response.success) {} else {
							console.error('Failed to update quantity:', response.data);
						}
					},
					error: function(xhr, status, error) {
						console.error('AJAX error:', status, error);
					}
				});
			}
		});
	});
</script>

<?php do_action('woocommerce_after_mini_cart'); ?>