使用循环更新购物车项目元

时间:2018-03-16 10:04:50

标签: wordpress woocommerce hook-woocommerce

我无法在购物车的循环中更新第一个购物车商品元,其余正在正确更新。请帮我纠正这个问题。感谢。

 <div class="lm-item ">   
            <div class="lm-item-body">
             product A
              <div class="lm-item-link">
              <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>
              <a href="abc.com/shop/?c=12,13,45&b=1315,1314,1313&add-to-cart=430">add to cart</a>
              <input type="hidden" class="product_id" value="430">
              </div>
            </div>  
          </div>
          <div class="lm-item ">   
            <div class="lm-item-body">
             product B
              <div class="lm-item-link">
              <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>
              <a href="abc.com/shop/?c=12,13,45&b=1315,1314,1313&add-to-cart=431">add to cart</a>
              <input type="hidden" class="product_id" value="431">
              </div>
            </div>  
          </div>
        <script>
        jQuery(document).ready(function($) {
            $(document).on('click','.lm-item-link a',function (e) { 
             e.preventDefault();
                var product_id = $(this).siblings('.product_id').val();
                var category_id = '12,13';   
                var board_id = '1315,1314';             
                $.ajax({
                        url: '<?php echo admin_url("admin-ajax.php");?>',
                        type:"POST",
                        data:{ 
                            category_id: category_id,
                            board_id: board_id,
                            product_id: product_id,
                            action: 'custom_add_product_to_cart',
                        },
                        success: function( data ) { 
                            console.log(data);      
                            $("#result").html(data);
                        }
                });         
            });
        });  
        </script>

2.使用此功能使用购物车项目键更新购物车项目元。

// ============ function cart cart item meta to cart ==================== //

 function custom_add_product_to_cart() {
    global $wpdb;
    $category_id = $_POST['category_id'];
    $board_id = $_POST['board_id'];  
    $category_ids_array = explode(',', $category_id);
    $board_ids_array = explode(',', $board_id); 
    $product_id = $_POST['product_id'];
            foreach($board_ids_array as $board_id){
                foreach($category_ids_array as $category_id){               
                     $key = WC()->cart->add_to_cart($product_id);

      WC()->cart->cart_contents[$key]['board_title'] = $board_name; 
                WC()->cart->cart_contents[$key]['board_id'] = $board_id; 
                WC()->cart->cart_contents[$key]['slot_id'] = $slot_id; 
                }
            }
    die();
    }   

0 个答案:

没有答案