0

default add video button enter image description hereI import all product by custom script. but I'm not able to import the product video programmatically. Basically, I have youtube link of videos. I can put url the using admin panel but I have 3000 product so, i can't do that way. I want to add Video progrmatically.

2 Answers 2

3

like addImageMedieGallery function we should extend the \Magento\Catalog\Model\Product\Gallery\Processor for adding video to product gallery,

product =  $this->productRepository->get($sku);
$videoData = [
            'video_id' => "test1", 
            'video_title' => "title", 
            'video_description' => "description",
            'thumbnail' => "image path", 
            'video_provider' => "youtube",
            'video_metadata' => null,
            'video_url' => "https://www.youtube.com/watch?v=test",
            'media_type' => \Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::MEDIA_TYPE_CODE,
        ];
$videoData['file'] = $videoData['video_id'] . 'filename.jpg';  //download thumbnail image and save locally under pub/media
f ($product->hasGalleryAttribute())
        {
            $this->videoGalleryProcessor->addVideo(
                $product,
                $videoData,
                ['image', 'small_image', 'thumbnail'],
                false,
                true
            );
        }
$this->productRepository->save($product);

$this->videoGalleryProcessor ( create an custom file for video process that extend the \Magento\Catalog\Model\Product\Gallery\Processor )

We have to create Vendor\Module\Model\Product\Gallery\Video\Processor file in our module.

<?php
namespace Vendor\Module\Model\Product\Gallery\Video;
use Magento\Framework\Exception\LocalizedException;
class Processor extends \Magento\Catalog\Model\Product\Gallery\Processor
{
    /**
     * @var \Magento\Catalog\Model\Product\Gallery\CreateHandler
     */
    protected $createHandler;
    /**
     * Processor constructor.
     * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository
     * @param \Magento\MediaStorage\Helper\File\Storage\Database       $fileStorageDb
     * @param \Magento\Catalog\Model\Product\Media\Config              $mediaConfig
     * @param \Magento\Framework\Filesystem                            $filesystem
     * @param \Magento\Catalog\Model\ResourceModel\Product\Gallery     $resourceModel
     * @param \Magento\Catalog\Model\Product\Gallery\CreateHandler     $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;
}
/**
 * @param \Magento\Catalog\Model\Product $product
 * @param array                          $videoData
 * @param [type]                         $mediaAttribute
 * @param boolean                        $move
 * @param boolean                        $exclude
 */
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;
}
}

Hope this will help you , Thanks.

8
  • What do I put in value_id? Because randomly putting value is the wrong way to do it. Is there any way to fetch the last insert ID. and tell what path is set in the thumbnail? The Thumbnail path is for where we save the image or already saved image path.
    – Galib
    Dec 29, 2022 at 14:25
  • For value I'd is auto generated and for thumbnail image its save the image path. Dec 29, 2022 at 15:28
  • I set everything confused in 2 attributes (' thumbnail','$videoData['file']'). What I fill in these fields My Image path is "/home/adminmaster/public_html/pub/media/catalog/product/2877vdo.jpg." please help with this Because error comes: Product SKU: 24877. The image does not exist.
    – Galib
    Dec 29, 2022 at 19:12
  • Please, if you know the answer, tell me.
    – Galib
    Dec 30, 2022 at 11:24
  • Use pub media folder path , not use the SKU for this.Luke filename is absdc.jpg as a/b/absdc.jpg Dec 30, 2022 at 13:13
0

Create an product custom attribute if you are not created earlier for youtube link.
Use your custom script or cron, loop through the products and initiate product Repository interface "Magento\Catalog\Api\ProductRepositoryInterface" and get the product by SKU or Magento product id and set the values for video_url and video_title attribute value respectively and save the product repository.

Before that please ensure you added youtube API Key enter image description here

Sample code snippet as ,

private $productRepository; 
...
public function __construct(
    ...
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ...
) {
    ...
    $this->productRepository = $productRepository;
    ...
}

public function loadMyProduct($sku,$youtubeLink) {
    $product =  $this->productRepository->get($sku);
    $product->setData('video_url', 'video url');
    $product->setData('video_title', 'video title');
    $this->productRepository->save($product);
}
8
  • There are Magento default features to add the video. Why make the other attributes
    – Galib
    Dec 27, 2022 at 3:54
  • I thought you were going by custm attribute. please try with default attribute code here Dec 27, 2022 at 4:10
  • There is no default attribute code showing.
    – Galib
    Dec 27, 2022 at 8:10
  • Please, if you know the answer, tell me.
    – Galib
    Dec 28, 2022 at 14:35
  • Answer section is updated now. please check and revert if this helpful . Dec 28, 2022 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.