Skip to content

Instantly share code, notes, and snippets.

@sc0ttkclark
Forked from kloon/gist:2376300
Last active March 5, 2020 08:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sc0ttkclark/839dbad77c62fba36d1368718bb4e982 to your computer and use it in GitHub Desktop.
Save sc0ttkclark/839dbad77c62fba36d1368718bb4e982 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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
Copy link

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