-
-
Save sc0ttkclark/839dbad77c62fba36d1368718bb4e982 to your computer and use it in GitHub Desktop.
WooCommerce Automatically add product to cart on site visit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
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?
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
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