In this tutorial we’ll learn how to add a product automatically to cart when a user/customer navigates to cart.
Here is my cart and currently it is empty.
Find the product id of the product you want to automatically add to cart. Let’s say for this example I want to add product 1 automatically to cart when an user/customer moves to cart page.
To find the product id go to backend end and click on products. It will display a list of products.
Click on product 1 to edit / see its id.
Now open the function.php file of your theme. You can access the function.php file here:
Add the following lines of code at the end of the file.
function add_product_to_cart() { if ( ! is_admin() ) { global $woocommerce; $product_id = 8; $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' );
Now when the user/ sutomer will navigate to cart specified product will be added to cart.