Add a Variation to Cart using AJAX - WooCommerce API?

后端 未结 2 674
广开言路
广开言路 2020-11-27 17:28

I have an item with the following data :

var item = {
  id : \"124\",
  name : \"xxx\",
  price : \"13.13\",
  quantity : 1,
  options : {
    \"size\" : \"x         


        
2条回答
  •  悲&欢浪女
    2020-11-27 18:19

    If anyone is interested I've also written a "remove from cart" function to counter the add to cart. My project called for radio buttons on checkout so I needed to add a product and remove the alternative it was already there:

    Here's the php:

    function remove_from_cart( $product_id ) {
        $cart_contents  = WC()->cart->get_cart();
    
        if (empty($product_id)) { $product_id = $_POST['product_id']; }
    
        foreach ($cart_contents as $product_key => $product){
            if ($product['variation_id'] == $product_id){
                WC()->cart->remove_cart_item($product_key);
            }
        }
    }
    
    add_action( 'wp_ajax_nopriv_remove_from_cart', 'remove_from_cart' );
    

    And then here's the jQuery:

    function remove_item_from_cart(product){
    
        var data = {
                    "action" : "remove_from_cart",
                    "product_id" : product,
        };
    
        jQuery.post(WC_VARIATION_ADD_TO_CART.ajax_url, data, function(response) {
            $(document.body).trigger("update_checkout");
        });
    
    }
    

    The if(empty)... in the php was so I could call the function from the server side as well if I needed to.

提交回复
热议问题