Display Shopify product video conditionally on product page layout

I’m working on a Shopify store where some products include both images and videos while others only have images. I want to display the video prominently on the product page when it exists, rather than having customers scroll through dozens of images to find it.

I’m trying to place the video element below the purchase button on the right side of the product page. I’ve identified the correct template file to modify but I’m struggling with the Liquid logic to detect if a video exists and display it accordingly.

Here’s my current attempt:

{% for media_item in product.media %}
  {% if media_item.media_type == 'video' %}
    Video found!
    <video controls width="300" height="200">
      <source src="{{ media_item.sources[1].url }}" type="video/mp4">
      Browser doesn't support video playback.
    </video>
    {% break %}
  {% endif %}
{% endfor %}

The code currently only shows the product name regardless of whether a video exists or not. Each product has at most one video file. Could someone guide me on what I might be doing wrong with this approach?

The problem’s probably with how Shopify structures media objects. Don’t access media_item.sources[1].url directly - try media_item.preview_image.alt first to check if the media object loads properly. Then use media_item | video_tag: controls: true, width: 300, height: 200 for the actual video. This filter grabs the source URLs automatically and works way better than building the video element yourself. Shopify’s video handling gets weird when you access the sources array directly. The video_tag filter also handles fallbacks for different formats and browser issues. Just make sure you’re testing with videos actually uploaded through Shopify admin, not file URLs dumped into metafields.

Your Liquid syntax looks right for detecting video media types, but there’s probably an issue with how you’re grabbing the video URL. I’ve hit this same problem with Shopify’s media objects. Try media_item.sources.first.url instead of media_item.sources[1].url - that index might not point to what you think it does. Also throw in some debugging output to make sure your media loop is actually finding videos. Check if your video files are properly processed by Shopify too. New uploads sometimes need time to process before they show up in the media API. You can verify this in your product admin’s media section. If it’s still broken, wrap your video code in a conditional that checks if the sources array has data before trying to access it.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.