Site icon MageComp Blog

How to Create Downloadable Product Programmatically in Magento 2

Hello Magento Folks,

Welcome to Create Product Programmatically in Magento 2 series where I will help you learn How to Create Downloadable Product Programmatically in Magento 2.

Mainly we can create 6 types of products Programmatically in Magento 2:

Basically downloadable products are the products which the customers will require to download such as eBook, music, video, software application, etc. You can enable your customers to log in and get the link or send the link via email. Eventually when you are creating a massive amount of downloadable products then it is very complicated and becomes time-consuming. Instead of doing this confusing thing you can directly create downloadable products programmatically. Check out the below code.

Steps to Create Downloadable Product Programmatically in Magento 2:

Step 1 : Firstly, create a downloadable_product.php file in the Magento root directory after adding the below code.

<?php
use Magento\Framework\AppInterface;
try {
    require_once __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
    $downloadable_product = $objectManager->create('Magento\Catalog\Model\Product');
    $downloadable_product->setName('Downloadable Product Name'); // set Downloadable Product Name
    $downloadable_product->setTypeId('downloadable'); // Set Product Type Id (simple/virtual/downloadable/configurable/grouped/bundle)
    $downloadable_product->setAttributeSetId(4); // Set Attribute Set ID
    $downloadable_product->setSku('downloadable_product_sku'); // Set Downloadable Product SKU
    $downloadable_product->setStatus(1); // status enabled/disabled 1/0
    $downloadable_product->setTaxClassId(0); // Set Tax Class Id
    $downloadable_product->setWebsiteIds([1]); // Set Website Ids
    $downloadable_product->setVisibility(4); // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))
    $category_id = array(2, 3);
    $downloadable_product->setCategoryIds($category_id); // Assign Category Ids
    $downloadable_product->setPrice(100); // Downloadable Product Price
    $downloadable_product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 1000
        )
    );
    try {
        $downloadable_product->save();
        $link_interface = $objectManager->create('\Magento\Downloadable\Api\Data\LinkInterface');
        $link_interface->setTitle('Downloadable Product Sample Link Title');
        $link_interface->setPrice(99);
        $link_interface->setNumberOFDownloads(10);
        $link_interface->setIsShareable(1);
        $link_interface->setLinkType('url');
        $link_interface->setLinkUrl('https://yourdomain/test.png');
        $link_interface->setSampleType('url');
        $link_interface->setSampleUrl('https://yourdomain/test.png');
        $link_interface->setIsUnlimited(0);
        $link_interface->setSortOrder(0);
        $link_repository_interface = $objectManager->create('Magento\Downloadable\Api\LinkRepositoryInterface');
        $link_repository_interface->save($downloadable_product->getSku(), $link_interface);
        $sample_interface = $objectManager->create('\Magento\Downloadable\Api\Data\SampleInterface');
        $sample_interface->setTitle('Downloadable Product Sample Title');
        $sample_interface->setSampleType('url');
        $sample_interface->setSampleUrl('https://yourdomain/test.png');
        $sample_interface->setSortOrder(0);
        $sample_repository_interface = $objectManager->create('Magento\Downloadable\Api\SampleRepositoryInterface');
        $sample_repository_interface->save($downloadable_product->getSku(), $sample_interface);
        if ($downloadable_product->getId()) {
            echo "Downloadable Product Created Successfully.";
        }
    }catch (\Exception $e) {
        echo $e->getMessage();
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

Step 2: After the above step run the below URL.

https://yourdomain.com/downloadable_product.php

Note*: Magento has added this feature in latest 2.3.3 You have to whitelist the domains of those links through ssh in order to save them. To add a domain you have to run the below command :

php bin/magento downloadable:domains:add www.yourdomain.com

In order to get all whitelisted domains use the below command

php bin/magento downloadable:domains:show

In order to remove a domain from whitelist

php bin/magento downloadable:domains:remove www.yourdomain.com

Wrap Up:

Hopefully, all are able to create Downloadable Product Programmatically in Magento 2  using the code above. If you come across any error during creating Downloadable Product Programmatically then let me know in the comment section below I will help you there. As per the nature of Magento always make sure you clear cache and reindex to display output on the frontend of your Magento 2 store. You can also take the help of our certified Magento Developers. 

Don’t forget to share the tutorial with your Magento Friends via social media channels

Happy Reading!

Exit mobile version