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

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

<a id="buy" href="#" rel="nofollow noreferrer noopener">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]

Method 2

In PHP I managed to do it this way:

global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);

The method is in woocommerce/classes/class-wc-cart.php:

    /**
     * Add a product to the cart.
     *
     * @param string $product_id contains the id of the product to add to the cart
     * @param string $quantity contains the quantity of the item to add
     * @param int $variation_id
     * @param array $variation attribute values
     * @param array $cart_item_data extra cart item data we want to pass into the item
     * @return bool
     */
    public function add_to_cart( $product_id, $quantity = 1, $variation_id = '', $variation = '', $cart_item_data = array() ) {


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x