Automatically add product to cart on visit in WooCommerce
Add this code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Dessky Snippets plugin. Please don’t add custom code directly to your parent theme’s functions.php file as this will be overwritten completely when you update the theme.
/** * Automatically add product to cart on visit */ add_action( 'template_redirect', 'add_product_to_cart' ); function add_product_to_cart() { if ( ! is_admin() ) { $product_id = 64; //replace with your own product id $found = false; //check if product already in cart if ( sizeof( WC()->cart->get_cart() ) > 0 ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; if ( $_product->get_id() == $product_id ) $found = true; } // if product not found, add it if ( ! $found ) WC()->cart->add_to_cart( $product_id ); } else { // if no products in cart, add it WC()->cart->add_to_cart( $product_id ); } } }