How to Add Product to Cart Programmatically Woocommerce

Do you want a WooCommerce add to cart option that can help you enhance client experience and increase sales?


January 19, 2023

In this piece, you'll discover how to utilise a WordPress hook to programmatically apply a "add to cart" function so consumers can simply find the goods they desire in the checkout.

Add code to your child theme's functions.php file or use a plugin that enables adding custom functions, such as the Code Snippets plugin.

add_action( 'wp', 'cxc_woocommerce_add_product_to_cart' ); function cxc_woocommerce_add_product_to_cart() { $product_id = 10; // product ID to add to cart WC()->cart->empty_cart(); WC()->cart->add_to_cart( $product_id ); }

If you have an online business, you will most likely sell a variety of items, which you will be able to add to the add-to-cart feature. 

But one of the things I've never understood about WooCommerce is how the Add to Cart function works for single goods. When you click the Add to Cart button, the default function reloads the whole page.

That's all there is to it, fellas! You should now have a WooCommerce add-to-cart function working on your store. Please contact us with any inquiries or to share your experience.