Knowledge Base

Help, guides and FAQ about Magikcommerce.

Automatically Add Products to Cart on Visit?


In WooComemrce normally product added in cart when you click on the add to cart button. But if you want to add the product to the cart on the visit  then you have to follow the steps given below.

Automatically add products to cart on visit

To automatically add products to cart on the visit you need to add the following lines of code in your theme's functions.php file. Just append the following lines of code at the bottom of functions.php

function magik_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', 'magik_add_product_to_cart' );

If you face any problems or need our professional services, please email us at [email protected] .