Creating Downloadable Product Programmatically in Magento 2

Downloadable products in Magento allows the store owner to sell digital files, like eBooks, music, video tutorials, software applications or updates. After the shopper completed their purchase, based on the downloadable product’s configuration, require the customer to log in to their account to receive the link, or can be sent an email with a link to download a file and they can share the link with others. Also, can be limited the number of downloads in the product configuration.

In Magento 2 admin panel, you can create any number of products. But if you need to create a downloadable product with an external script, this article will help you.

Initialize Object Manager And Set Area Code

While creating an external script, It is very important to include the below code in the top of the file,

use Magento\Framework\App\Bootstrap;

/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;

$bootstrap = Bootstrap::create(BP, $params);

The purpose of the above code is used to access the Magento 2 core functionality from your external file.

Moving on, use the below script to set the area code as adminhtml,

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

Create Downloadable Product

Use the below code to create the downloadable product programmatically.

As you may know that in order to create new product in Magento 2, it’s necessary to use the following two classes in your custom script.

  • \Magento\Catalog\Api\Data\ProductInterfaceFactory
  • \Magento\Catalog\Api\ProductRepositoryInterface
$productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$product = $productInterfaceFactory->create();

// Get the default attribute set id
$attributeSetId = $product->getDefaultAttributeSetId();

$sku = $urlKey = 'test-downloadable-product';
$product->setSku($sku)
		->setName('Test Downloadable Product')
		->setUrlKey($urlKey)
		->setAttributeSetId($attributeSetId)
		->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
		->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
		->setTypeId(\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE)
		->setWebsiteIds([1])
		->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
		->setPrice(100)
		->setStockData(
			[
				'use_config_manage_stock' => 0,
				'manage_stock' => 1,
				'is_in_stock' => 1,
				'qty' => 999999
			]
		);

$product = $productRepository->save($product);

if ($product->getId()) {
	echo 'Product Created Successfully';
}

Set Downloadable Information To Product

Use the below code to set the downloadable information to the product. For instance, I use the downloadable link type as URL.

$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$baseUrl = $storeManager->getStore()->getBaseUrl();

$linkRepository = $objectManager->create('Magento\Downloadable\Api\LinkRepositoryInterface');
$linkInterface = $objectManager->create('Magento\Downloadable\Api\Data\LinkInterface');
$linkInterface->setTitle('Downloable Product');
$linkInterface->setPrice(9);
$linkInterface->setNumberOFDownloads(10);
$linkInterface->setIsShareable(1);
$linkInterface->setLinkType('url');
$linkInterface->setLinkUrl($baseUrl . 'file.zip');
$linkInterface->setSampleType('url');
$linkInterface->setSampleUrl($baseUrl . 'sample.zip');
$linkInterface->setIsUnlimited(0);
$linkInterface->setSortOrder(0);
$linkRepository->save($product->getSku(), $linkInterface);

// To add data under sample section
$sampleRepository = $objectManager->create('Magento\Downloadable\Api\SampleRepositoryInterface');
$sampleInterface = $objectManager->create('Magento\Downloadable\Api\Data\SampleInterface');
$sampleInterface->setTitle('Sample Product');
$sampleInterface->setSampleType('url');
$sampleInterface->setSampleUrl($baseUrl . 'sample.jpg');
$sampleInterface->setSortOrder(0);
$sampleInterface->save($product->getSku(), $sampleRepository);

Add Images To Product

Then, use the code below which is used to add the images to the product, Before running this script, the images should be placed in the pub/media/import/ folder.

$filesystem = $objectManager->create('Magento\Framework\Filesystem');
$mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaPath = $mediaDirectory->getAbsolutePath();
$imagePath = $mediaPath .'import/sample.jpg'; // path of the image
$product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
$product->save();

Here is the complete code to create a downloadable product programmatically in Magento 2 and set downloadable information to it using a custom external script.

<?php
use Magento\Framework\App\Bootstrap;
 
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
 
$objectManager = $bootstrap->getObjectManager();
 
// Set area code
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need

try {
    $productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

    $product = $productInterfaceFactory->create();

    // Get the default attribute set id
    $attributeSetId = $product->getDefaultAttributeSetId();

    $sku = $urlKey = 'test-downloadable-product';
    $product->setSku($sku)
            ->setName('Test Downloadable Product')
            ->setUrlKey($urlKey)
            ->setAttributeSetId($attributeSetId)
            ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
            ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
            ->setTypeId(\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE)
            ->setWebsiteIds([1])
            ->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
            ->setPrice(100)
            ->setStockData(
                [
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => 999999
                ]
            );

    $product = $productRepository->save($product);

    if ($product->getId()) {
        echo 'Product Created Successfully';
    }

    $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
    $baseUrl = $storeManager->getStore()->getBaseUrl();

    $linkRepository = $objectManager->create('Magento\Downloadable\Api\LinkRepositoryInterface');
    $linkInterface = $objectManager->create('Magento\Downloadable\Api\Data\LinkInterface');
    $linkInterface->setTitle('Downloable Product');
    $linkInterface->setPrice(9);
    $linkInterface->setNumberOFDownloads(10);
    $linkInterface->setIsShareable(1);
    $linkInterface->setLinkType('url');
    $linkInterface->setLinkUrl($baseUrl . 'file.zip');
    $linkInterface->setSampleType('url');
    $linkInterface->setSampleUrl($baseUrl . 'sample.zip');
    $linkInterface->setIsUnlimited(0);
    $linkInterface->setSortOrder(0);
    $linkRepository->save($product->getSku(), $linkInterface);

    // To add data under sample section
    $sampleRepository = $objectManager->create('Magento\Downloadable\Api\SampleRepositoryInterface');
    $sampleInterface = $objectManager->create('Magento\Downloadable\Api\Data\SampleInterface');
    $sampleInterface->setTitle('Sample Product');
    $sampleInterface->setSampleType('url');
    $sampleInterface->setSampleUrl($baseUrl . 'sample.jpg');
    $sampleInterface->setSortOrder(0);
    $sampleInterface->save($product->getSku(), $sampleRepository);

    $filesystem = $objectManager->create('Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    $imagePath = $mediaPath .'import/sample.jpg'; // path of the image
    $product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
    $product->save();

} catch (\Exception $e) {
    echo $e->getMessage();
}

You may also like:

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *