Domanda

How to get product video as base and thumbnail in product listing page. Currently, Only Video preview image is showing in listing page. But I want to display video in listing page instead of the preview image.

È stato utile?

Soluzione

You can get Media collection of particular product by loading it in custom helper as below:

<?php
namespace Your\Module\Helper;

use Magento\Catalog\Api\ProductRepositoryInterface;

class Data extends \Magento\Framework\Url\Helper\Data
{
    public function __construct(
        ...
        ProductRepositoryInterface $productRepository,
        ...
    ) {
        ...
        $this->productRepository = $productRepository;
        ...
    }

    public function getMediaGalleryImages($product)
    {
        $_product = $this->productRepository->get($product->getSku(), false, null, true);

        return $_product->getMediaGalleryImages();
    }
}

Please copy

vendor/magento/module-catalog/view/frontend/templates/product/list.phtml

to your custom theme.

app/design/frontend/package/theme/Magento_Catalog/templates/product/list.phtml

Now in list.phtml file, you can call this function to load the video url if it's available otherwise show the regular image:

<?php
$video = false;
$galleryImages = $this->helper('Your\Module\Helper\Data')->getMediaGalleryImages($_product);
if ($galleryImages) {
    foreach ($galleryImages as $primage) {
        $imageData = $primage->getData();
        // Check media type
        if (isset($imageData['media_type']) && $imageData['media_type'] == 'external-video') {
            $video = true;
            if (strpos($imageData['video_url'], 'youtube.com') !== false) {
                echo preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"240\" height=\"300\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>", $imageData['video_url']);
            }elseif(strpos($imageData['video_url'], 'vimeo.com') !== false){
                echo "<iframe width=\"240\" height=\"300\" src=".$imageData['video_url']." frameborder=\"0\" allowfullscreen></iframe>";
            }
        }
    }
}
?>

<?php if(!$video){ ?>
    <?= $productImage->toHtml() ?>
<?php } ?>

For vimeo, add embedded urls for product video to make them playable at list page. Please note that it would take some extra time to load page first time as we are loading product to get media collection.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top