Skip to content

Instantly share code, notes, and snippets.

@corsonr
Created December 7, 2013 11:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save corsonr/7839908 to your computer and use it in GitHub Desktop.
Save corsonr/7839908 to your computer and use it in GitHub Desktop.
Automatically add product to cart on visit - WooCommerce
/*
* Add item to cart on visit
*/
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 64;
$found = false;
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
add_action( 'init', 'add_product_to_cart' );
@tsfact
Copy link

tsfact commented Dec 29, 2015

Hi corsonr,
First of all, thank you for your time making this snippet.
I have tried this one but it seems that the "user" cannot delete the added item if wish, which mean that this snippet is useless & counterproductive. If the users cannot delete the item (apart from annoying them a lot) then they will never go to checkout with a item that they do not want to. In other words, the potential client would be lost.

If there is a way to fix this, I would appreciate a reply.

Many thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment