WooCommerce add_to_cart

admin2025-06-06  8

I'm creating a WooCommerce product programmatically (Create product via CRUD) and wants to add it to its cart.

Code I'm using is marked as legacy (WC_Cart)

$cart = new WC_Cart();
$cart->add_to_cart($product_id);

The question: Is there a newer way to add product(s) to the cart?

I'm creating a WooCommerce product programmatically (Create product via CRUD) and wants to add it to its cart.

Code I'm using is marked as legacy (WC_Cart)

$cart = new WC_Cart();
$cart->add_to_cart($product_id);

The question: Is there a newer way to add product(s) to the cart?

Share Improve this question asked Nov 21, 2018 at 6:51 TungstenXTungstenX 652 silver badges10 bronze badges 5
  • 2 You can use WC()->cart->add_to_cart(). – Sally CJ Commented Nov 21, 2018 at 6:54
  • @SallyCJ Thank you. I can't seem to find any documentation of the WC class on docs.woocommerce – TungstenX Commented Nov 21, 2018 at 7:22
  • You can find it here for the main WooCommerce class. WC() is a wrapper function for the instance of that class, and WC()->cart is the WC_Cart instance, so there's no need to new WC_Cart(). And there's a snippet here which might be helpful to you. :) – Sally CJ Commented Nov 21, 2018 at 7:49
  • @SallyCJ please make this an answer ;-) – TungstenX Commented Nov 21, 2018 at 8:08
  • I posted an answer. I hope that it will be helpful to you and other folks. ;) (sorry for the delay, my laptop was misbehaving) – Sally CJ Commented Nov 21, 2018 at 14:36
Add a comment  | 

1 Answer 1

Reset to default 1

The question: Is there a newer way to add product(s) to the cart?

Well, WC_Cart::add_to_cart() is still the way to do it.

Except (on the front-end), there's no need to reinstantiate the cart class:

$cart = new WC_Cart();

because the main WooCommerce class already instantiates WC_Cart, and you can easily access the class instance like so:

$cart = wc()->cart;
//$cart = WC()->cart; // same as above, but wc() (i.e. lowercase) is actually preferred :)

where wc() is a wrapper function that returns the main instance of the main WooCommerce class.

And to add a product into the cart, you can use either of these options:

// Option #1
wc()->cart->add_to_cart( $product_id );

// Option #2: Here we assign wc()->cart to a variable.
$cart = wc()->cart;
$cart->add_to_cart( $product_id );

Hope that helps! :)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749163024a316896.html

最新回复(0)