Practical Way To Programmatically Create Downloadable Product In Magento 2
Magento 2 downloadable product is any product that you can deliver in the form of a file.
There are six product types in Magento 2:
- Simple Product
- Configurable Product
- Grouped Product
- Virtual Product
- Bundle Product
- Downloadable Product
Out of these, the downloadable products, are such as an ebook, music, video, or text file, or a software application.
As a store owner, you can configure the products to be able to access based on the login status of the customer. Also, you can deliver the product to the customers directly by allowing them to download from your site or send them via an email.
The downloadable products can be uploaded to the server or linked to from another server. Also, you can allow the customers to download the product for the specific number of times. The delivery of a downloadable product can be made when the order is in either a Pending
or Invoiced
state.
Learn the easy way to programmatically create downloadable product in Magento 2 with the below code.
Method to programmatically create downloadable product in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?php use Magento\Framework\App\Bootstrap; include('app/bootstrap.php'); $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager $product = $objectManager->create('\Magento\Catalog\Model\Product'); try { $product->setSku('sku'); // Set your sku here $product->setName('Product Name'); // Name of Product $product->setAttributeSetId(4); // Attribute set id $product->setStatus(1); // Status on product enabled/ disabled 1/0 $product->setWeight(10); // weight of product $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually) $product->setTaxClassId(0); // Tax class id $product->setTypeId('downloadable'); // type of product (simple/virtual/downloadable/configurable) $product->setPrice(500); // price of product $product->setLinkType('url'); // Set Link Type $product->setLinkUrl('path of url'); // Set Url Link $product->setSampleType('url'); // Set simple Link Type $product->setSampleUrl('url'); // Set Simple Url Link $product->setStockData( array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 40 ) ); // Adding Image to product $mediaDir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList')->getPath('media'); $imagePath = "image.jpg"; // path of the image $imageFilename = basename($imagePath); $image_type = substr(strrchr($imageFilename, "."), 1); //find the image extension $filename = md5($imagePath . strtotime('now')) . '.' . $image_type; //give a new name, you can modify as per your requirement if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true); else chmod($mediaDir, 0777); $filepath = $mediaDir . '/catalog/product/' . $filename; //path for temp storage folder: pub/media file_put_contents($filepath, file_get_contents(trim($imagePath))); //store the image from external url to the temp storage folder $imgUrl = $filepath; $product->addImageToMediaGallery($imgUrl, ['image', 'small_image', 'thumbnail'], false, false); $product->save(); // Adding Custom option to product $options = array( array( "sort_order" => 1, "number_of_downloads" => 10, "is_shareable" => 1, "link_url" => "http://example.com", "link_type" => "url", "sample_url" => "http://example.com", "sample_type" => "url" ) ); 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) { print_r($e->getMessage()); } ?> |
Any doubts in the implementation of creating Magento 2 downloadable products? Please mention them in the Comments section below. I’d be happy to help.
I’d be grateful if you help me share the post with Magento folks via your social media profiles.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
HI Sanjay, thanks for the example!
Maybe can you provide an example where the downloadable is type FILE and not URL. I am struggling to get it working. I know it needs a JSON encoded block to describe the file as i have it working on M1 but M2 says it can’t find the file when saving the product although i know it’s there on the server.
Hello,
Please refer the below code:
$link_repository = $objectManager->create('Magento\Downloadable\Api\LinkRepositoryInterface');
$link_interface = $objectManager->create('\Magento\Downloadable\Api\Data\LinkInterface');
$link_interface->setTitle('product title');
$link_interface->setPrice(20);
$link_interface->setNumberOFDownloads(30);
$link_interface->setIsShareable(1);
$link_interface->setLinkType('url');
$link_interface->setLinkUrl('Enter url here');
$link_interface->setSampleType('url');
$link_interface->setSampleUrl('Enter url here');
$link_interface->setIsUnlimited(0);
$link_interface->setSortOrder(0);
$link_repository->save('new sku', $link_interface); // param1 is the sku of your product
} catch (\Exception $e) {
print_r($e->getMessage());
}
Thanks.