-
-
Save grayayer/de7da3914c3de030fc50dd22cccc367e to your computer and use it in GitHub Desktop.
WooCommerce Automatically add product to cart on site visit
This file contains 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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or you can try the one at https://docs.woocommerce.com/document/automatically-add-product-to-cart-on-visit/