Magento 2:- Create a downloadable product programmatically

Follow my previous blogpost to create a simple product with magento that will give you a basic idea of creating products. In this blogpost we will continue from that post only. So to create product as downloadable, we need to set weight as NO and add details under downloadable Information tab.
In previous post code just set typeId as downloadable and product has weight to NO. After creating a product with type downloadable we have to add a link and sample data information for the product. To add a link use the below code.

$link_repository = $objectManager->create('Magento\Downloadable\Api\LinkRepositoryInterface');
$link_interface = $objectManager->create('\Magento\Downloadable\Api\Data\LinkInterface');
$link_interface->setTitle('first downloable product');
$link_interface->setPrice(9);
$link_interface->setNumberOFDownloads(10);
$link_interface->setIsShareable(1);
$link_interface->setLinkType('url');
$link_interface->setLinkUrl('http://www.w3solver.com');
$link_interface->setSampleType('url');
$link_interface->setSampleUrl('http://w3solver.com');
$link_interface->setIsUnlimited(0);
$link_interface->setSortOrder(0);
$link_repository->save('sku', $link_interface); // param1 is the sku of your product

To add data under sample section:-

$sample_repository = $objectManager->create('Magento\Downloadable\Api\SampleRepositoryInterface');
$sample_interface = $objectManager->create('\Magento\Downloadable\Api\Data\SampleInterface');
$sample_interface->setTitle('first downloable product');
$sample_interface->setSampleType('url');
$sample_interface->setSampleUrl('http://www.w3solver.com/download/qrcode.zip');
$sample_interface->setSortOrder(0);
$sample_repository->save('sku', $sample_interface);

In below you can see the data added to our product:-

Leave a Comment.