The product pages on any eCommerce store are the most important. And therefore, it is crucial to make them more attractive and effective.
Now, there are dozens of ways to make product pages more effective, but adding a product video is one of the proven ways to make them more attractive and share maximum information about the products.
In this tutorial, we’re going to teach you how to add a video to a product page programmatically in your Magento 2 based eCommerce store.
Steps to Add a Video to a Product Page Programmatically in Magento 2
In order to add a video programmatically, we first need to do the configuration for API.
Here, we will use Youtube API to add product videos in a Magento 2 store.
Step - 1
To add Youtube Videos programmatically in Magento 2 store, we need to generate the Youtube API key.
And for that, you need to follow the below instructions.
- Login to your Google account, open Google Developers Console and select your project.
- Next, click on the library menu button given at the left corner of the page.
- Once you click, you will be automatically redirected to the Youtube Data API page. Now find and click the Enable button on the same page.
- Next, go to Credential Menu where you will see your API key. You need to copy that API key.
- Now, open the Admin Panel of your Magento 2 eCommerce Store and paste the API key into Store -> Configuration -> Catalog -> Catalog -> Product Video -> YouTube API Key & save the configuration.
Step - 2
The next step is to create a module. For that, you can check out our tutorial on How to Create a Simple Module in Magento 2.
Once you have created the module, we now need to create a controller Test.php file inside app/code/MD/Helloworld/Controller/Index directory to add the product video.
After you have created the Test.php file, copy the below code.
<?php namespace MD\Helloworld\Controller\Index; use Magento\Framework\App\Action\Action; class Test extends Action { protected $videoGalleryProcessor; protected $_product; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Catalog\Model\Product $product, \MD\Helloworld\Model\Product\Gallery\Video\Processor $videoGalleryProcessor ){ parent::__construct($context); $this->_product = $product; $this->videoGalleryProcessor = $videoGalleryProcessor; } public function execute() { $productId = 1; // product id $product = $this->_product->load($productId); $product->setStoreId(0); //set store vise data // sample video data $videoData = [ 'video_id' => "abc", //set your video id 'video_title' => "title", //set your video title 'video_description' => "description", //set your video description 'thumbnail' => "image path", //set your video thumbnail path. 'video_provider' => "youtube", 'video_metadata' => null, 'video_url' => "https://www.youtube.com/watch?v=abc", //set your youtube channel's video url 'media_type' => \Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::MEDIA_TYPE_CODE, ]; //download thumbnail image and save locally under pub/media $videoData['file'] = $videoData['video_id'] . 'filename.jpg'; // Add video to the product if ($product->hasGalleryAttribute()) { $this->videoGalleryProcessor->addVideo( $product, $videoData, ['image', 'small_image', 'thumbnail'], false, true ); } $product->save(); } }
Step - 3
Now, we need to create a Processor.php file for implementing video processor in the app/code/MD/Helloworld/Model/Product\Gallery/Video directory and add the following code:
<?php namespace CompanyName\ModuleName\Model\Product\Gallery\Video; use Magento\Framework\Exception\LocalizedException; class Processor extends \Magento\Catalog\Model\Product\Gallery\Processor { protected $createHandler; public function __construct( \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository, \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageDb, \Magento\Catalog\Model\Product\Media\Config $mediaConfig, \Magento\Framework\Filesystem $filesystem, \Magento\Catalog\Model\ResourceModel\Product\Gallery $resourceModel, \Magento\Catalog\Model\Product\Gallery\CreateHandler $createHandler ) { parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel); $this->createHandler = $createHandler; } public function addVideo( \Magento\Catalog\Model\Product $product, array $videoData, $mediaAttribute = null, $move = false, $exclude = true ) $file = $this->mediaDirectory->getRelativePath($videoData['file']); if (!$this->mediaDirectory->isFile($file)) { throw new LocalizedException(__('The image does not exist.')); } $pathinfo = pathinfo($file); $imgExtensions = ['jpg', 'jpeg', 'gif', 'png']; if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) { throw new LocalizedException(__('Please correct the image file type.')); } $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($pathinfo['basename']); $dispretionPath = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName); $fileName = $dispretionPath . '/' . $fileName; $fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath); $destinationFile = $this->mediaConfig->getTmpMediaPath($fileName); try { /** @var $storageHelper \Magento\MediaStorage\Helper\File\Storage\Database */ $storageHelper = $this->fileStorageDb; if ($move) { $this->mediaDirectory->renameFile($file, $destinationFile); //Here, filesystem should be configured properly $storageHelper->saveFile($this->mediaConfig->getTmpMediaShortUrl($fileName)); } else { $this->mediaDirectory->copyFile($file, $destinationFile); $storageHelper->saveFile($this->mediaConfig->getTmpMediaShortUrl($fileName)) } } catch (\Exception $e) { throw new LocalizedException(__('We couldn\'t move this file: %1.', $e->getMessage())); } $fileName = str_replace('\\', '/', $fileName); $attrCode = $this->getAttribute()->getAttributeCode(); $mediaGalleryData = $product->getData($attrCode); $position = 0; if (!is_array($mediaGalleryData)) { $mediaGalleryData = ['images' => []]; } foreach ($mediaGalleryData['images'] as &$image) { if (isset($image['position']) && $image['position'] > $position) { $position = $image['position']; } } $position++; unset($videoData['file']); $mediaGalleryData['images'][] = array_merge([ 'file' => $fileName, 'label' => $videoData['video_title'], 'position' => $position, 'disabled' => (int)$exclude ], $videoData); $product->setData($attrCode, $mediaGalleryData); if ($mediaAttribute !== null) { $product->setMediaAttribute($product, $mediaAttribute, $fileName); } $this->createHandler->execute($product); return $fileName; } }
And done!
Now you need to just clean the cache and remove the generated/generation folder.
Also read: How to Add Custom Product Video in Fotorama Gallery?
Conclusion
By following this tutorial, we hope that you have now learned how to add a video to a product programmatically in Magento 2.
Remember, adding product videos can add a lot of value in terms of attracting and convincing customers to make a purchase.
So, go ahead and start adding videos to your product pages right away. And if you face any difficulties and need our help, you can contact us anytime.