Magento – Get product video

magento2product-imagesvideo

I have added some videos to my product via the add video section under product "Images And Videos". I want to be able to display the videos added this way in a custom section. The code currently looks like this:

$images = $full_product->getMediaGalleryImages();
foreach($images as $image){
  if(in_array($image->getFile(), $used_images)){
    continue;
  }
  ?>
  <li>
    <?php
    if($image->getMediaType() == "external-video") { 
      ?>
      <iframe width="640" height="480" src="<?php echo $image->getVideoUrl(); ?>" frameborder="0" allowfullscreen></iframe>
      <?php
    } else { // general show an image
    ?>
      <img src="<?php echo $image->getUrl(); ?>" alt="<?php echo $_productNameStripped; ?>" />
    <?php } ?>
  </li>
<?php } ?>

I want to display only certain images and videos in the list (hence the $used_images bit), so far it is working fine except the getVideoUrl for youtube returns me a wrongly formatted youtube url.

I get:
https://www.youtube.com/watch?v=abcdefghij

but I need:
https://www.youtube.com/embed/abcdefghij

It's possible for me to write some php code that would pull out the video code and get me the correct url but I want to know if their are magento methods for this or displaying videos/iframes. Creating my own methods shortcut here might cause me problems with other magento features (such as vimeo videos) not working in this display.

Best Answer

Write code like that call

preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>", $image->getVideoUrl());
Related Topic