• Skip to primary navigation
  • Skip to main content
OsomCode

OsomCode

Awesome code tutorials for WordPress and Genesis

  • Subscribe
  • My account
    • Edit profile
    • Favorites
    • Update credit card
  • Login

Automatically add a product to cart in WooCommerce

Learn in this tutorial how to add automatically a product to the cart when another one is added without plugins.

Are you interested that when the customer adds a certain product to the cart, another one is automatically added? That is, when the customer enters “Product A” in their cart, “Product B” is also added.

This is an interesting strategy if you want to give away for free a product at checkout.

There are some plugins that allow you to do this. But this is OsomCode, so… Do you want to accomplish the same thing with as little code as possible?

Here’s how to do it:

Snippet to automatically add a product to WooCommerce cart at checkout

Add the following code at the end of functions.php or in your functionality plugin:

To see this and another 839 code snippets of this website, login or subscribe here.

In this particular example, with the code you are indicating that when the customer adds “Product 2” (with ID=1752), “Product 6” (with ID=1744) should be also added to the cart.

WooCommerce-cart-product-added-automatically

To customize it you have to change the two product IDs to the ones you are interested in:

  • $product_id === 1752
  • $extra_product_id = 1477

With that you have it.

Conclusion

As you can see, you can automatically add a product to the WooCommerce cart when the customer chooses another product without the need for plugins.

Any questions? I read you in the comments.

And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉

PHP Products WooCommerce

To leave read and make questions about this code, you can login or register.

  • About OsomCode
  • FAQ
  • Contact

Legal Notice · Privacy Policy · Cookie Policy · Terms and conditions
Copyright © 2023

Lost your password?