Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace "add to cart" with custom quantity input fields in WooCommerce

I am using WooCommerce with Storefront theme to build an eCommerce website that will be used on smartphones mostly. So I am trying to reduce the number of clicks and buttons to make it as simple as possible.

I would like to replace "add to cart" button with a quantity selector :

for instance

I found a way to add a quantity selector next to "add to cart" button (e.g. with plugin WooCommerce Advanced Product Quantities) but I would like to get rid of "add to cart" button. So, when a customer click on "+", it should add 1 element to the cart and the number should display the quantity in the cart.

Also (no idea if this is possible...), I'd like an animation to notify the customer that the product was well added to the cart. For instance, show a "+1" for a few seconds near the cart icon,

like that

like image 881
AnneC Avatar asked Aug 16 '17 09:08

AnneC


1 Answers

here you go it's going to be long one :

First Let's Remove the Add To Cart Button:

// Remove Add To cart Button
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);

Now Lets Create our Input and add it to shop page

// Add our Quanity Input
add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
    global $product;
    ?>
    <div class="shopAddToCart">
    <button  value="-" class="minus"  >-</button>
    <input type="text"
    disabled="disabled"
    size="2"
    value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
    ?>"
    id="count"
    data-product-id= "<?php echo $product->get_id() ?>"
    data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0;
    ?>"
    data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
    ?>"
    class="quantity  qty"
    max_value = <?php echo ($product->get_max_purchase_quantity() == -1) ? 1000 : $product->get_max_purchase_quantity(); ?>
    min_value = <?php echo $product->get_min_purchase_quantity(); ?>
    >

    <button type="button" value="+" class="plus"  >+</button>

    </div>
                          <?php
}

we need to have function to check if the products is already in cart or not so can modify the quantity:

//Check if Product in Cart Already
function Check_if_product_in_cart($product_ids)
 {

foreach (WC()->cart->get_cart() as $cart_item):

    $items_id = $cart_item['product_id'];
    $QTY = $cart_item['quantity'];

    // for a unique product ID (integer or string value)
    if ($product_ids == $items_id):
        return ['in_cart' => true, 'QTY' => $QTY];

    endif;

endforeach;
}

we need to add custom event in order to reduce the quantity:

//Add Event Handler To update QTY
add_action('wc_ajax_update_qty', 'update_qty');

function update_qty()
{
    ob_start();
    $product_id = absint($_POST['product_id']);
    $product = wc_get_product($product_id);
    $quantity = $_POST['quantity'];

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item):

        if ($cart_item['product_id'] == $product_id) {
            WC()->cart->set_quantity($cart_item_key, $quantity, true);
        }

    endforeach;

    wp_send_json('done');
}

Finally We need Javascript to handle the event actions :

jQuery(document).ready(function ($) {
  "use strict";

  // Add Event Listner on the Plush button 
  $('.plus').click(function () {

    if (parseInt($(this).prev().val()) < parseInt($(this).prev().attr('max_value'))) {
      $(this).prev().val(+$(this).prev().val() + 1);

      var currentqty = parseInt($(this).prev().attr('data-in-cart-qty')) + 1;

      var id = $(this).prev().attr('data-product-id');

      var data = {
        product_id: id,
        quantity: 1
      };
      $(this).prev().attr('data-in-cart-qty', currentqty);
      $(this).parent().addClass('loading');
      $.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {

        if (!response) {
          return;
        }

        if (response) {

          var url = woocommerce_params.wc_ajax_url;
          url = url.replace("%%endpoint%%", "get_refreshed_fragments");
          $.post(url, function (data, status) {
            $(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
            if (data.fragments) {
              jQuery.each(data.fragments, function (key, value) {

                jQuery(key).replaceWith(value);
              });
            }
            jQuery("body").trigger("wc_fragments_refreshed");
          });
          $('.plus').parent().removeClass('loading');

        }

      });


    }




  });



  $('.minus').click(function () {

    $(this).next().val(+$(this).next().val() - 1);


    var currentqty = parseInt($(this).next().val());

    var id = $(this).next().attr('data-product-id');

    var data = {
      product_id: id,
      quantity: currentqty
    };
    $(this).parent().addClass('loading');
    $.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_qty'), data, function (response) {

      if (!response) {
        return;
      }

      if (response) {
        var url = woocommerce_params.wc_ajax_url;
        url = url.replace("%%endpoint%%", "get_refreshed_fragments");
        $.post(url, function (data, status) {
          $(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
          if (data.fragments) {
            jQuery.each(data.fragments, function (key, value) {

              jQuery(key).replaceWith(value);
            });
          }
          jQuery("body").trigger("wc_fragments_refreshed");
        });
        $('.plus').parent().removeClass('loading');
      }

    });




  });



});

Note: This code is tested and working you can check it at

http://dev-ak.com/woocommerce-dev/shop/

You can download the whole files from :

https://github.com/kashalo/wc_qty_ajax_stroefront_child.git

Regarding the Animation part in footer cart that of course can be done, and if i have some free time i will do it too.

like image 171
kashalo Avatar answered Nov 17 '22 15:11

kashalo