Add Product to Cart if Cart Empty Woocommerce

Add Product to Cart if Cart Empty Woocommerce

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

<?php
  add_action( 'template_redirect', 'woocommerce_add_product_to_cart' );
   
  function woocommerce_add_product_to_cart() {
    $product_id = 123; // Product ID
     // if cart empty, add it to cart
     if ( WC()->cart->get_cart_contents_count() == 0 ) {
        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 *