Magento 2: How to create a downloadable product programmatically
-
16-12-2020 - |
Pergunta
I try to create a import job but I do not know how to create a downloadable product programmatically.
https://www.mageplaza.com/magento-2-create-product-programmatically.html
I readed this site but I have no idea how to do that. How can I insert the download link to the product ? Please advise.
Solução
Try this. It should work.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$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.example.com');
$link_interface->setSampleType('url');
$link_interface->setSampleUrl('http://example.com');
$link_interface->setIsUnlimited(0);
$link_interface->setSortOrder(0);
$link_repository->save('your_product_sku', $link_interface);
// 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.example.com/download/file.zip');
$sample_interface->setSortOrder(0);
$sample_repository->save('your_product_sku', $sample_interface);
Note: Do not use objectManager directly. Use dependency injection.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange