Custom add to cart button to add multiple product into cart with quantity :woocommerce

后端 未结 3 1812
北荒
北荒 2021-02-06 11:22

I want to create custom add to cart button to add my 3 product into cart with 2 quantity for each..

For add three product into cart I have done using like this:

3条回答
  •  一个人的身影
    2021-02-06 12:14

    Save products id in array and make ajax request

     jQuery("#addSelected").click(function() {  var arrayLength =
     arrayOfAddedProducts.length;   jQuery.ajax({
             type: "POST",
             url: ajaxurl,
             data: {action : 'add_item_from_cart','getIDtoAdd' : arrayOfAddedProducts},
             success: function (res) {
                wc_load_all_products();
             }
         }); });
    

    function.php

    function add_item_from_cart() {
       foreach ($_POST['getIDtoAdd'] as $productId) {
          WC()->cart->add_to_cart( intval($productId), 1, 0, array(), array() );
        // WC()->cart->add_to_cart( $product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() );
       }
    }
    
    add_action('wp_ajax_add_item_from_cart', 'add_item_from_cart');
    add_action('wp_ajax_nopriv_add_item_from_cart', 'add_item_from_cart');
    

提交回复
热议问题