Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce Automatically add product to cart on site visit
<?php
/*
* This code goes into theme functions.php or a custom plugin
*/
/**
* Add product to cart on page load
*/
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 123; // Product ID to auto-add
$variation_id = 124; // Set to 0 if no variation
if ( empty( $product_id ) ) {
return;
}
// Get WC Cart
$cart = WC()->cart;
// Get WC Cart items
$cart_items = $cart->get_cart();
// Check if product is already in cart
if ( 0 < count( $cart_items ) ) {
foreach ( $cart_items as $cart_item_key => $values ) {
$_product = $values['data'];
// Product is already in cart, bail
if ( $_product->id == $product_id ) {
return;
}
}
}
// Add product to cart
$cart->add_to_cart( $product_id, 1, $variation_id );
// Calculate totals
$cart->calculate_totals();
// Save cart to session
$cart->set_session();
// Maybe set cart cookies
$cart->maybe_set_cart_cookies();
}
}
add_action( 'template_redirect', 'add_product_to_cart' );
@dereck13

This comment has been minimized.

Copy link

commented Oct 12, 2016

Hi a very useful bit of code BUT
wont let me delete the product from the cart and
for whatever reason will only add 1 unit even though there have been say 2 items selected (want one addon per product number bought)
and it does not seem to pick up the price from the product file.
I am using woocommerce bookings
Hope you can help
Regards
Dereck Gray, Dunedin NZ

@tsunamimarketing2

This comment has been minimized.

Copy link

commented Jun 7, 2017

How would I edit this code in order to make it only add the product to the cart if a specific coupon code is applied to the cart?

@urbanadventurer

This comment has been minimized.

Copy link

commented Dec 8, 2017

It raises a warning with the latest version of WooCommerce unless you use get_id()
if ( $_product->get_id() == $product_id ) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.