How to Automatically add product to cart on visit in WooCommerce

This is a tiny WordPress code snippet, I came across while wondering around the internet. Basically, what this code do is it automatically adds a product to cart as soon as a user visits your website.

Useful Read: Set a minimum order for cart total – WooCommerce

Note: Change 120 with your own custom Product ID.

/*
 * Automatically add product to cart on visit
 **/
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
	if ( ! is_admin() ) {
		global $woocommerce;
		$product_id = 120;
		$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 );
		}
	}
}

Source: woothemes.com

0 Comments

Leave a Comment.