How to Create a Simple Product Programmatically in Magento 2

How to Create a Simple Product Programmatically in Magento 2

While development or testing, you may need a huge amount of products. Magento 2 has the feature to create the products from the backend but there is the time at which you want to create multiple products to test page performance, you need to create products in a certain format, you have some custom attribute or you have created your own attribute set or product type. It’s when you need to create products programmatically to ease the task and save the time. Here, I’ve come up with the custom code to implement to create a simple product programmatically in Magento 2!

There are six product types in Magento 2:

  1. Simple Product
  2. Configurable Product
  3. Grouped Product
  4. Virtual Product
  5. Bundle Product
  6. Downloadable Product

The below method allows creating simple product programmatically along with custom options. Moreover, you can add images to the media gallery of the product with the below method.

 

Create a Simple Product Programmatically in Magento 2:

 

That’s it and we have created a simple product quickly! If you still can’t see it on the frontend, reindex and clear your cache.

This is the easiest method possible, however, if you get stuck in the implementation, please mention it in the comments section below and I’d be happy to help!

If you opt to create a simple product in Magento 2 from the admin panel, refer here.

Flash 5 stars for the post if found useful?

Happy Coding!

Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

5
(based on 18 Reviews)

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. Owing to his contributions in Magento Forums and posting solutions, he is among the top 50 contributors of the Magento community in 2019. When he is not engrossed with anything related to Magento, he loves to play cricket.

3 comments On How to Create a Simple Product Programmatically in Magento 2

  • Your not wrong, whats happening is that while your code works once, try running it again setting the SKU to a different value, while every other value such as name and description is correctly changing the setSku is retained. for example my first itteration i setSku(‘product1’) second time in my loop i setSku(‘product2’) but if i do a getSku on the product it shows “product1”

  • I used to use code like this to create multiple products into my 2.2 site, but as of upgrading to 2.3 the code hangs on the second product_>save itteration. Not sure why as yet.

    • Dominic, the current code works well for Magento 2.3. It seems like your catalog product table is having duplicate entry of SKU or URL key and that’s why showing this issue.

Leave a reply:

Your email address will not be published.