Magento, Magento 2

How to Create Virtual Product Programmatically in Magento 2

How to Create Virtual Product Programmatically in Magento 2

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

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

You may also like this :

Let’s create the script for that. Create virtual.php file at your Magento’s root folder and this below code :

<?php
/**
 * Created By : Rohan Hapani
 */
use Magento\Framework\App\Bootstrap;

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

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product = $objectManager->create('Magento\Catalog\Model\Product');

try {
    $product->setName('Virtual Product'); // Set Product Name
    $product->setTypeId('virtual'); // Set Product Type Id
    $product->setAttributeSetId(4); // Set Attribute Set ID
    $product->setSku('virtual-product'); // Set SKU
    $product->setWebsiteIds([1]); // Set Website Ids
    $product->setVisibility(4); // Set Visibility
    $product->setPrice(100); // Set Price
    $product->setImage('/virtual/test.jpg'); // Image Path
    $product->setSmallImage('/virtual/test.jpg'); // Small Image Path
    $product->setThumbnail('/virtual/test.jpg'); // Thumbnail Image Path
    $product->setStockData(
        [
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'min_sale_qty' => 1,
            'max_sale_qty' => 2,
            'is_in_stock' => 1,
            'qty' => 100,
        ]
    );
    $product->save();
    if ($product->getId())
    {
        echo "Product Created Successfully";
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

That’s it !!

In addition, You can set static details based on your requirements. If you want to create multiple products programmatically by the script at that time, you can use this script and customize code for multiple products create.

Now, execute this file at frontend side : {baseUrl}/virtual.php

I hope this blog will helpful for easily understand how to create a virtual product programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing 🙂

 

 

Tagged ,