🔥 Just Launched! Werra Premium Template for HyväSee it in Action

Simplest Way To Programmatically Create Virtual Product In Magento 2

By Sanjay JethvaUpdated on May 22, 2025 2 min read

Magento 2 Virtual Products are the non-tangible products that can’t be touched and have no weight.

There are six product types in Magento 2:

  1. Simple Product
  2. Configurable Product
  3. Grouped Product
  4. Virtual Product
  5. Bundle Product
  6. Downloadable Product

The virtual products are products such as memberships, services, warranties, subscriptions, or any type of digital file. They are sold either individually or with grouped or bundle products. The perfect example of a virtual product is an ebook or a gym membership.

Here’s the easy method to programmatically create virtual product in Magento 2.

Method to programmatically create virtual product in Magento 2:

<?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
try {
    $product = $objectManager->create('Magento\Catalog\Model\Product');
    $product->setSku('Main Virtual'); // Set your sku here
    $product->setName('Virtual Color Product'); // 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('virtual'); // type of product (simple/virtual/downloadable/configurable)
    $product->setPrice(500); // price of product
    $product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 200
        )
    );
// Adding Image to product
    $mediaDir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList')->getPath('media');
    $imagePath = "logo.jpg"; // path of the image
    $imageFilename = basename($imagePath);
    $image_type = substr(strrchr($imageFilename,"."),1);
    $filename = md5($imagePath . strtotime('now')).'.'.$image_type;
    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)));
    $imgArray  = $filepath;
    $product->addImageToMediaGallery($imgArray, array('image', 'small_image', 'thumbnail'), false, false);
    $product->save();
// Adding Custom option to product
    $options = array(
        array(
            "sort_order" => 1,
            "title" => "Custom Option 1",
            "price_type" => "fixed",
            "price" => "10",
            "type" => "field",
            "is_require" => 0
        ),
        array(
            "sort_order" => 2,
            "title" => "Custom Option 2",
            "price_type" => "fixed",
            "price" => "20",
            "type" => "field",
            "is_require" => 0
        )
    );
    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){
    echo $e->getMessage();
}

That’s it.

Please share this post with the Magento community via social media profiles.

Thank you.

Sanjay Jethva Full Image
Article bySanjay 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.