How to create product programmatically in Magento 2?

- Advertisement -

Magento 2 has the feature to create Product Programmatically 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 time. Here, I’ve come up with the custom code to implement to create a simple product programmatically in Magento 2!

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:

- Advertisement -
<?php use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');

$product = $objectManager->create('Magento\Catalog\Model\Product');

try {
    $product->setName('Test Product');
    $product->setTypeId('simple');
    $product->setAttributeSetId(4);
    $product->setSku('test-SKU');
    $product->setWebsiteIds(array(1));
    $product->setVisibility(4);
    $product->setPrice(array(1));
    $product->setImage('/testimg/test.jpg');
    $product->setSmallImage('/testimg/test.jpg');
    $product->setThumbnail('/testimg/test.jpg');
    $product->setStockData(array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'min_sale_qty' => 1,
            'max_sale_qty' => 2,
            'is_in_stock' => 1,
            'qty' => 100
        )
    );

    $product->save();

    // Adding Custom option to product
    $options = array(
        array(
            "sort_order" => 1,
            "title" => "Custom Option 1",
            "price_type" => "fixed",
            "price" => "10",
            "type" => "field",
            "is_require" => 0
        ),
        array(
            "sort_order" => 2,
            "title" => "Custom Option 2",
            "price_type" => "fixed",
            "price" => "20",
            "type" => "field",
            "is_require" => 0
        )
    );
    foreach ($options as $arrayOption) {
        $product->setHasOptions(1);
        $product->getResource()->save($product);
        $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
            ->setProductId($product->getId())
            ->setStoreId($product->getStoreId())
            ->addData($arrayOption);
        $option->save();
        $product->addOption($option);
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

- Advertisement -

Note: There are some points you need to remember when using this code snippet.

1- If you want to create a configurable product then you have to assign associated product to current product otherwise it will create a simple product.

2- If you do not set weight, it will create a simple product.

3- If you want to create a downloadable product then you have to add download links to current product otherwise it will create virtual/simple product.

- Advertisement -

Share it with friends:

Related Articles

Laravel – SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables….

SQLSTATE No such file or directory   While setting up MySQL, I am getting the following error: Command-line code: testLaravel1 php artisan migrate SQLSTATE No such...

How to create best Bootstrap FAQ template? [Full Source Code]

Bootstrap FAQ Bootsrap Frequently Asked Questions. bootstrap faq, bootstrap faq template, bootstrap 4 faq template, bootstrap 3 faq template, bootstrap compost faq, faq in...

Old Instagram Logo with HTML and CSS quality logo

Create the Old Instagram Logo by HTML and CSS. Old Instagram Logo CSS  for new style Instagram logo  logo.html <div class="Instagram"> <span class="Instagram-strip"></span> <span class="Instagram-viewfinder"></span> ...

Chrome plans to start blocking resource-heavy ads in August Update

Chrome plans to start blocking resource-heavy ads that drain a lot of battery in August, Google announced today on its Chromium blog (via VentureBeat). Chrome...

How to create Sitemaps on Blogger for Google and Bing

Create Sitemaps on Blogger The XML Sitemap file is like a directory of all web pages that exist on your website or blog. Google,...

How to speed up WordPress with Plesk and WP Super Cache, WP Rocket, Autoptimize Free

https://websavers.ca/how-to-speed-up-wordpress   This guide includes 9 tips to show you how to take just about any WordPress site to a maximum 1-2 seconds load time. If you’ve...

Get in Touch

163FansLike
115FollowersFollow

Latest Posts

Laravel – SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables….

SQLSTATE No such file or directory   While setting up MySQL, I am getting the following error: Command-line code: testLaravel1 php artisan migrate SQLSTATE No such...

How to create best Bootstrap FAQ template? [Full Source Code]

Bootstrap FAQ Bootsrap Frequently Asked Questions. bootstrap faq, bootstrap faq template, bootstrap 4 faq template, bootstrap 3 faq template, bootstrap compost faq, faq in...

Old Instagram Logo with HTML and CSS quality logo

Create the Old Instagram Logo by HTML and CSS. Old Instagram Logo CSS  for new style Instagram logo  logo.html <div class="Instagram"> <span class="Instagram-strip"></span> <span class="Instagram-viewfinder"></span> ...

Chrome plans to start blocking resource-heavy ads in August Update

Chrome plans to start blocking resource-heavy ads that drain a lot of battery in August, Google announced today on its Chromium blog (via VentureBeat). Chrome...

How to create Sitemaps on Blogger for Google and Bing

Create Sitemaps on Blogger The XML Sitemap file is like a directory of all web pages that exist on your website or blog. Google,...

Popular Posts

This is the proposed SpaceX internet plan. WOW

Sometime in 2019, SpaceX will be launching the first of its proposed 4000 satellites to provide ultra-high speed internet to the entire world. This is...

Instagram Logo CSS gradient with HTML best 2 quality logo

The new Instagram logo create by CSS gradient. Read more about Gradient here Instagram logo CSS and HTML Method - 1 logo.html &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn. com/font-awesome/4.3.0/css/font-awesome.min.css"&gt; &lt;span class="instagram"&gt; ...

Failed to execute ‘postMessage’ on ‘DOMWindow’: https://www.accounts.google.com !== http://yourdoamin.com

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://accounts.google.com') does not match the recipient window's origin ('https://www.yourdomain.com') What is the problem actually? How to...

DB import failure at CREATE ALGORITHM = UNDEFINED DEFINER Error: #1227 – Access denied – Fixed

CREATE ALGORITHM=UNDEFINED [email protected]`%` SQL SECURITY INVOKER VIEW...  When import the SQL file from localhost to remote server, if the server is shared or not given...

XAMPP Port 443 ERROR in Windows with VMware

When we used XAMPP and VM Ware or any Virtual machine on the same PC we can't run XAMPP or WAMP properly because Virtual machine...