Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

How to automatically add product to cart on visit in WooCommerce?

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.

Our team at Themelocation is comprised of WordPress developers of high expertise

  • We can maintain, support and manage your single, or all your clients, website with dedication
  • Our skills are at your disposal.

Book a Call

woocommerceFind 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.

woocommerceClick on product 1 to edit / see its id.

woocommerceNote the id of the product.

Now open the function.php file of your theme. You can access the function.php file here:

woocommerceAdd 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.

woocommerce

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *