简体   繁体   English

用 WooCommerce 中的自定义数量输入字段替换“添加到购物车”

[英]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.我正在使用带有店面主题的 WooCommerce 来构建一个主要用于智能手机的电子商务网站。 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 :我想用数量选择器替换“添加到购物车”按钮:

例如

I found a way to add a quantity selector next to "add to cart" button (eg with plugin WooCommerce Advanced Product Quantities) but I would like to get rid of "add to cart" button.我找到了一种在“添加到购物车”按钮旁边添加数量选择器的方法(例如使用插件 WooCommerce 高级产品数量),但我想摆脱“添加到购物车”按钮。 So, when a customer click on "+", it should add 1 element to the cart and the number should display the quantity in the cart.因此,当客户点击“+”时,它应该向购物车添加 1 个元素,并且数字应该显示购物车中的数量。

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,例如,在购物车图标附近显示“+1”几秒钟,

像那样

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 :最后我们需要 Javascript 来处理事件动作:

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/ http://dev-ak.com/woocommerce-dev/shop/

You can download the whole files from :您可以从以下位置下载整个文件:

https://github.com/kashalo/wc_qty_ajax_stroefront_child.git 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.关于页脚购物车中的动画部分,当然可以完成,如果我有空闲时间,我也会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自定义添加到购物车按钮,将多个产品添加到购物车中,数量:woocommerce - Custom add to cart button to add multiple product into cart with quantity :woocommerce 设置自定义添加到购物车默认数量(Woocommerce 购物车页面除外) - Set custom Add to cart default quantity except on Woocommerce cart page 在 WooCommerce 商店页面上添加数量字段并添加到购物车按钮 - Adding quantity fields and add to cart buton on WooCommerce Shop page 设置最小输入量,甚至在Woocommerce中添加到购物车的ajax上 - Set minimum input quantity even on ajax add to cart in Woocommerce WooCommerce商店页面:添加到购物车按钮上的数量输入 - WooCommerce Shop page: Quantity input on add to cart button woocommerce_quantity_input在添加到购物车循环中不起作用 - woocommerce_quantity_input doesn't work in add to cart loop 通过add_to_cart的WooCommerce自定义字段 - WooCommerce Custom Fields through add_to_cart 在Woocommerce中根据购物车数量添加自定义结帐字段 - Add a custom checkout field based on cart items quantity in Woocommerce 将WooCommerce上的添加到购物车按钮替换为自定义按钮 - Replace add to cart button with a custom button on WooCommerce 在 Woocommerce 购物车页面上添加自定义输入字段 - Add Custom Input Field on Woocommerce Cart Page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM