Magento 2 being a multifunctional e-commerce platform allows you to create products from the admin panel. There are plenty of options to fill out to create a simple product in Magento 2, which obviously takes some time.

And what if you have to create a huge amount of products, especially during the development or testing? 

The easiest, in this case, would be to create products programmatically. And that is exactly what you're going to learn in this article.

Use the following method to create a simple product in Magento 2 programmatically:

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();
}

Was it difficult?

It's the easiest way to create simple products with some custom attributes in Magento 2 programmatically. If you can't see the product on the frontend, reindex and clear Magento 2 cache.

However, as mentioned before, Magento allows you to create multiple product types. So if you're interested, check out this guide on Ultimate Guide to Magento 2 Product Types and learn more about other product types, their differences and management tips.