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 |1 Answer
Reset to default 1The 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! :)
WC()->cart->add_to_cart()
. – Sally CJ Commented Nov 21, 2018 at 6:54WC()
is a wrapper function for the instance of that class, andWC()->cart
is theWC_Cart
instance, so there's no need tonew WC_Cart()
. And there's a snippet here which might be helpful to you. :) – Sally CJ Commented Nov 21, 2018 at 7:49