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

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