Add Product to Cart Programmatically Woocommerce

how to add product to cart in woocommerce programmatically

We can add product to WooCommerce cart using add_to_cart() function with $product_id.

<?php
  add_action( 'wp', 'woocommerce_add_product_to_cart' );

  function woocommerce_add_product_to_cart() {
     $product_id = 123; // product ID to add to cart
     WC()->cart->empty_cart();
     WC()->cart->add_to_cart( $product_id ); 
  }

?>

Code goes in function.php file of your active child theme (or active theme).

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *