How7o
  • Home
  • Tools
  • Prank Screens
  • Contact
  • Blog
Reading: How to Automatically Add a Product to Cart on Visit in WooCommerce
Share
Subscribe Now
How7oHow7o
Font ResizerAa
  • Marketing
  • OS
  • Features
  • Guide
  • Complaint
  • Advertise
Search
  • Home
  • Tools
  • Prank Screens
  • Contact
  • Blog
Follow US
Copyright © 2014-2023 Ruby Theme Ltd. All Rights Reserved.
How7o > Blog > Web Development > How to Automatically Add a Product to Cart on Visit in WooCommerce
Web Development

How to Automatically Add a Product to Cart on Visit in WooCommerce

how7o
By how7o
Last updated: May 10, 2026
8 Min Read
WooCommerce auto add to cart on visit — template_redirect hook and cart dedup
SHARE

WooCommerce auto add to cart on a specific page is a template_redirect hook plus WC()->cart->add_to_cart(). The pattern: check if we’re on the right page, figure out which product IDs should be in the cart, skip any that are already there, add the rest. This guide covers the hook, the dedup logic that keeps refreshes from stacking duplicates, and the meta-flag variant when you want to manage the product list without editing code.

Contents
  • TL;DR
  • Why template_redirect is the right hook
  • The dedup logic
  • Meta-flag variant — marketing-managed list
  • Variable products
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-04-23 on WooCommerce 9.x with WordPress 6.5. Originally published 2023-06-25, rewritten and updated 2026-04-23.

TL;DR

add_action( 'template_redirect', 'how7o_auto_add_products_to_cart' );

function how7o_auto_add_products_to_cart() {
    if ( ! is_page( 'start' ) ) {
        return;
    }

    $product_ids = array( 10, 12, 15 );

    // Drop IDs already in the cart
    foreach ( WC()->cart->get_cart() as $item ) {
        $key = array_search( $item['data']->get_id(), $product_ids, true );
        if ( $key !== false ) {
            unset( $product_ids[ $key ] );
        }
    }

    foreach ( $product_ids as $id ) {
        WC()->cart->add_to_cart( $id );
    }
}

Why template_redirect is the right hook

The sequence on a typical request:

  • init — WordPress boots. WooCommerce is partially loaded; the cart object may not be ready.
  • wp — the main query has run; $wp_query exists.
  • template_redirect — WooCommerce is fully initialized, is_page() / is_product() work correctly, and no output has been sent yet so redirects and cart changes still apply.
  • wp_head — output has started.

template_redirect is the last safe stop where you can mutate the cart and have the changes reflect on the rendered page.

The dedup logic

$product_ids = array( 10, 12, 15 );

foreach ( WC()->cart->get_cart() as $item_key => $item ) {
    $existing_id = $item['data']->get_id();
    $key         = array_search( $existing_id, $product_ids, true );

    if ( $key !== false ) {
        unset( $product_ids[ $key ] );
    }
}

foreach ( $product_ids as $id ) {
    WC()->cart->add_to_cart( $id );
}

The dedup loop walks the cart’s existing items, and for every item that’s already in our “to add” list, removes it. After the loop, $product_ids contains only the products that aren’t in the cart yet. Without this check, a page refresh would call add_to_cart() again and the item’s quantity would climb each visit.

array_search‘s strict flag (true) matters — get_id() returns an int, and loose comparison against strings from the product list would silently mismatch.

woocommerce auto add to cart — template_redirect hook + dedup against existing cart items

Meta-flag variant — marketing-managed list

add_action( 'template_redirect', function () {
    if ( ! is_page( 'start' ) ) {
        return;
    }

    $query = new WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'meta_key'       => '_add_product_to_cart',
        'meta_value'     => 'yes',
    ) );

    $product_ids = $query->posts;

    foreach ( WC()->cart->get_cart() as $item ) {
        $key = array_search( $item['data']->get_id(), $product_ids, true );
        if ( $key !== false ) {
            unset( $product_ids[ $key ] );
        }
    }

    foreach ( $product_ids as $id ) {
        WC()->cart->add_to_cart( $id );
    }
} );

Products tagged with the custom meta _add_product_to_cart = 'yes' get auto-added on the landing page. Marketing can toggle the meta from the product edit screen (with a custom meta box or via ACF) — no code changes needed to change which product the flow promotes.

Note: 'fields' => 'ids' returns just an array of post IDs, which saves instantiating full WP_Post objects when you only need the IDs. See ordering posts by meta value for the WP_Query pattern behind this.

Variable products

WC()->cart->add_to_cart(
    $parent_id,
    1,
    $variation_id,                                 // specific variation
    array( 'attribute_pa_color' => 'red' )         // attribute selections
);

Variable products need the variation ID, quantity, and attribute array. Passing only the parent ID adds the parent product — which has no price and breaks the cart. If you’re auto-adding a variable product, the marketing-managed meta-flag variant needs to know which variation to pick; usually easier to list the variation IDs directly in the $product_ids array.

Frequently asked questions

Which hook fires for woocommerce auto add to cart?

template_redirect — it runs after WordPress has resolved which template will render but before the template actually outputs. That’s the right window to modify the cart: WooCommerce is fully loaded, the page context is known, and redirects still work if you need them. Hooking earlier (init) risks the cart not being ready; hooking later (wp_head) means you’ve already committed to rendering.

Why check the cart before adding?

WC()->cart->add_to_cart() is additive — call it twice and the product ends up with quantity 2, not 1. On a landing-page pattern where the user might refresh or come back, you want the auto-added product in the cart exactly once. Iterating the existing cart items, removing already-present IDs from the to-add list, then adding the rest, gives you that “once” guarantee.

Can I target specific pages?

Yes — wrap the whole thing in an is_page('landing-slug') or is_page_template('landing.php') check. For a coupon-landing flow you might only want to auto-add on /start/; for a lead-magnet download, only on /ebook-bonus/. Without a scope check, the cart is auto-populated on every page load — which is almost never what you want.

How do I choose which product IDs to add?

Two options. Hardcode an array ($product_ids = [10, 12, 15]) when the list is static. Or query products by a custom meta flag — for example _add_product_to_cart => 'yes' — so marketing can manage the list from the product admin without editing code. The source post shows both shapes.

Does this work with variable products?

WC()->cart->add_to_cart($product_id) with a parent ID adds the parent — which won’t have a price and will break the cart. Pass the variation ID instead: add_to_cart($parent_id, 1, $variation_id, $attributes). The fourth argument is the attribute array (['attribute_pa_color' => 'red']). For simple products, the first two args are enough.

Related guides

  • How to Add a Custom Fee in WooCommerce — another cart-modification pattern.
  • How to Remove Checkout Fields in WooCommerce — simplify the flow after auto-populating the cart.
  • How to Display Orders Instead of Dashboard on the WooCommerce My Account Page — post-purchase flow.
  • How to Order Posts by Meta Value in WordPress — WP_Query meta_key pattern behind the meta-flag variant.

References

WooCommerce “Automatically add product to cart on visit”: woocommerce.com/document/automatically-add-product-to-cart-on-visit.

TAGGED:phpWooCommercewordpress

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article WooCommerce add custom fee — woocommerce_cart_calculate_fees + WC()->cart->add_fee How to Add a Custom Fee (or Transaction Fee) in WooCommerce
Next Article WooCommerce orders as My Account default — menu filter + redirect How to Display Orders Instead of Dashboard on the WooCommerce My Account Page
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!
Most Popular
Display PHP errors — ini_set + php.ini configuration
How to Display PHP Errors
May 10, 2026
PHP convert string to uppercase — strtoupper and mb_strtoupper
How to Convert a String to Uppercase in PHP
May 10, 2026
PHP string to float conversion with cast, regex cleanup, NumberFormatter
How to Convert a String to Float in PHP
May 10, 2026
PHP merge arrays without duplicates — union operator and array_unique
How to Combine Two Arrays Without Duplicates in PHP
May 10, 2026
PHP delete array element — unset, array_splice, array_filter, array_search
How to Delete an Element from a PHP Array
May 10, 2026

You Might Also Like

Laravel validator exists rule checking a post_id against the posts table
Web Development

How to Use the Laravel Validator Exists Rule

6 Min Read
Laravel MySQL variable in select — @name := assignment chains values across select items
Web Development

How to Set a MySQL Variable in Laravel Query Builder Select

8 Min Read
WordPress posts by date range — date_query with after/before/inclusive
Web Development

How to Get Posts by Date Range in WordPress

7 Min Read
WordPress prepare LIKE SQL — %s placeholder + % wildcards in the value
Web Development

How to Prepare a %LIKE% SQL Statement in WordPress

7 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Latest News

  • SEO Audit Tool
  • Client ReferralsNew
  • Execution of SEO
  • Reporting Tool

Resouce

  • Google Search Console
  • Google Keyword Planner
  • Google OptimiseHot
  • SEO Spider

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?