While looking through various Magento 2 product types, you can't miss downloadable products. As the name suggests, these are digital products that can be downloaded — books, software, videos, etc. This type of content is becoming more and more popular these days. As a result, you can benefit greatly from having them in your store's catalogue.

Creating downloadable products via the admin panel may be rather challenging since it requires lots of steps. Fortunately, there is a programmatic way to optimize the process.

The following code will help you to create a downloadable product in Magento 2 programmatically:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');

try {
$product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);
$product
->setSku('sku') // Set your sku here
->setName('Product Name') // Name of Product
->setAttributeSetId(4) // Attribute set id
->setStatus(1) // Status on product enabled/ disabled 1/0
->setWeight(10) // weight of product
->setVisibility(4) // visibilty of product (catalog / search / catalog, search / Not visible individually)
->setTaxClassId(0) // Tax class id
->setTypeId('downloadable') // type of product (simple/virtual/downloadable/configurable)
->setPrice(500) // price of product
->setLinkType('url') // Set Link Type
->setLinkUrl('path of url') // Set Url Link
->setSampleType('url') // Set simple Link Type
->setSampleUrl('url') // Set Simple Url Link
->setStockData(
array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 40
)
);

// Adding Image to product
$imagePath = ""; //Set the path of Image for product
$product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
$product->save();

// Adding Custom option to product
$options = [
[
"sort_order" => 1,
"title" => "Field Option",
"price_type" => "fixed",
"price" => "",
"type" => "field",
"is_require" => 0
]
];

$product->setHasOptions(1);
$product->setCanSaveCustomOptions(true);
foreach ($options as $arrayOption) {

$option = $objectManager->create(\Magento\Catalog\Model\Product\Option::class)
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($arrayOption);

$option->save();
$product->addOption($option);
}

echo 'success';

} catch (\Exception $e) {
$objectManager->get(\Psr\Log\LoggerInterface::class)->info($e->getMessage());
echo $e->getMessage();
}

This is actually it! Quite easy, right?

If you master this method, then creating simple and configurable products in Magento 2 will be even easier, in case you don't know how to do it already.