Woocommerce – Add a product to cart programmatically via JS or PHP [closed]

I am using the Woocommerce plugin to facilitate a small e-commerce part of a site and need to add products to its cart via some call or function rather than using its own ‘add-to-cart’ buttons.

By this I basically mean send Woocommerce a SKU and quantity for example and have the cart update.

sendToCart('123456', 55);

etc

I’ve looked through the documentation and can’t seem to find a reference to this sort of thing. Can anyone suggest how I might achieve this?

2

OK so here’s how I solved it in the end. A quick and dirty example, uses JQuery.

<a id="buy" href="#">Buy this!</a>
    <script>    
       $('#buy').click(function(e) {
          e.preventDefault();
          addToCart(19);
          return false;
       });    

       function addToCart(p_id) {
          $.get('/wp/?post_type=product&add-to-cart=" + p_id, function() {
             // call back
          });
       }
    </script>

This just makes an AJAX GET request to the cart url

/wp/?post_type=product&add-to-cart=[PRODUCT_ID]

Leave a Comment