How to automatically add a WooCommerce product to cart on page load

WooCommerce recommends to automatically add a product to cart with a code snippet you can add to your (child-)themes functions.php:

This code works fine and is probably everything most shop owners need. But there is a scenario where this code doesn’t work or at least isn’t a good solution. The code always adds the product with a given ID to the Cart. It doesn’t matter if or which products you already have in cart. You can of course delete the product from the cart, but it comes back with the next page load.

So why can this be a problem?

Imagine you want to add a free physical product as a gift for your customers. Your intention is good, but if your store sells physical and downloadable products your customers will always have to pay for shipping if it isn’t free, even when they only have downloadable products in cart. This can be a problem. So I decided to tweak the code snippet a bit. The new code checks if there is any product in cart which requires shipping. If such a product is found it than adds the product of a given ID automatically:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
  if ( ! is_admin() ):

    // Search for a product that requires shipping
    $shippingProductDetected = 0;
    foreach ( WC()->cart->get_cart() as $cart_item ):
      $product =  wc_get_product( $cart_item['product_id']); 
      if( $cart_item['variation_id'] != 0 ):
        $product = wc_get_product($cart_item['variation_id']);
      if( $product->is_downloadable() == 1 ):
        $shippingProductDetected = 0;
        $shippingProductDetected = 1;

    $product_id = 3334; //replace with your own product id
    $found = false;
    //check if product already in cart
    if ( sizeof( WC()->cart->get_cart() ) > 0 ):
      foreach ( WC()->cart->get_cart() as $cart_item_key => $values ):
        $_product = $values['data'];
        if ( $_product->get_id() == $product_id ):
          $found = true;
      // if product not found and shipping product in cart found, add it
      if ( ! $found && $shippingProductDetected):
        WC()->cart->add_to_cart( $product_id );



Leave a Comment

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