Create Virtual Product Programmatically

Hello Friends!!


In this tutorial, I will explain to you how to create a virtual product programmatically in Magento 2. The Virtual Product represents non-tangible items such as membership, subscription, services, etc. You can sell virtual products individually or include them as part of the grouped product or bundle product types.

When we need to create a virtual product using a script instead of an admin panel. Then, how we can create it by script?

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

There are six product types in Magento 2:

• Simple Product

• Configurable Product

• Grouped Product

• Virtual Product

• Bundle Product

• Downloadable Product

Here, is the full-fledged solution to Create a Virtual Product Programmatically in Magento 2. 

Steps to Create Virtual Product Programmatically in Magento 2:

Step 1: Create a virtual_product.php file in the Magento root directory and add the below code


use Magento\Framework\AppInterface;

try {

    require_once __DIR__ . '/app/bootstrap.php';

} catch (\Exception $e) {

    echo 'Autoload error: ' . $e->getMessage();



try {

    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $appState = $objectManager->get('Magento\Framework\App\State');


    $virtual_product = $objectManager->create('Magento\Catalog\Model\Product');

    $virtual_product->setStatus(1); // status enabled/disabled 1/0

    $virtual_product->setName('Virtual Product Name'); // Set Your Virtual Product Name

    $virtual_product->setSku('virtual_product_sku'); // Set Virtual Product SKU

    $virtual_product->setTypeId('virtual');  // Set Product Type Id (simple/virtual/downloadable/configurable/grouped/bundle)

    $virtual_product->setAttributeSetId(4); // Set Attribute Set ID

    $virtual_product->setWebsiteIds(array(1)); // Set Website Ids

    $virtual_product->setTaxClassId(0); // Set Tax class ID

    $virtual_product->setVisibility(4); // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))

    $category_id = array(2, 3);

    $virtual_product->setCategoryIds($category_id); // Assign your to category using category Id

    $virtual_product->setPrice(199); // Set Virtual Product Price



            'use_config_manage_stock' => 0,

            'manage_stock' => 1,

            'min_sale_qty' => 1,

            'max_sale_qty' => 2,

            'is_in_stock' => 1,

            'qty' => 1000,




    if ($virtual_product->getId()) {

        echo "Virtual Product Created Successfully.";



catch(\Exception $e) {




After adding the above code, run the below URL


That’s it!


I hope this helps you! Any queries are appreciated through the comments section below.

Don’t forget to share this post with your Magento friends to help them out. Keep Learning! Keep Growing!

Thank You.