You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断Shopify产品是否含视频并在产品页指定位置展示?

Shopify产品详情页视频展示优化方案

问题根源

你原来的代码只盯着第一个媒体文件判断类型,如果产品首图是图片,哪怕后面有视频也白搭;而且image分支还会强制输出首图,完全不符合“没视频就啥也不显示”的要求。

优化代码&思路

1. 正确判断是否有视频

用Liquid的过滤器扫一遍所有媒体,只要有视频就触发渲染:

{% comment %} 检查产品里有没有视频媒体 {% endcomment %}
{% assign has_video = product.media | where: "media_type", "video" | size > 0 %}

{% if has_video %}
  {% comment %} 抓取第一个视频媒体 {% endcomment %}
  {% assign target_video = product.media | where: "media_type", "video" | first %}
  
  {% comment %} 在加购按钮下方渲染视频 {% endcomment %}
  <div class="product-video-wrap">
    <video controls width="100%" height="auto">
      <source src="{{ target_video.src }}" type="{{ target_video.content_type }}">
      你的浏览器不支持视频播放。
    </video>
  </div>
{% endif %}

2. 核心优化点

  • 全局排查视频存在性:不再局限于第一个媒体,只要产品包含视频就会触发渲染
  • 移除多余图片输出:无视频时不显示任何元素,完全匹配需求
  • 自动适配视频格式:用target_video.content_type替代硬编码的video/mp4,兼容不同视频格式
  • 响应式布局适配:宽度设为100%、高度自适应,适配手机/电脑等不同设备

3. 模板位置调整

把这段代码粘贴到产品详情页模板(通常是product.liquid或sections/product-template.liquid)中加入购物车按钮的HTML代码之后,示例如下:

{% comment %} 原有加入购物车按钮代码 {% endcomment %}
<button type="submit" class="add-to-cart-btn">加入购物车</button>

{% comment %} 视频渲染代码放在此处 {% endcomment %}
{% assign has_video = product.media | where: "media_type", "video" | size > 0 %}
{% if has_video %}
  {% assign target_video = product.media | where: "media_type", "video" | first %}
  <div class="product-video-wrap">
    <video controls width="100%" height="auto">
      <source src="{{ target_video.src }}" type="{{ target_video.content_type }}">
      你的浏览器不支持视频播放。
    </video>
  </div>
{% endif %}

4. 额外扩展玩法

如果需要展示产品所有视频,移除| first过滤器,用循环遍历即可:

{% if has_video %}
  <div class="product-video-list">
    {% for video in product.media | where: "media_type", "video" %}
      <video controls width="100%" height="auto">
        <source src="{{ video.src }}" type="{{ video.content_type }}">
        你的浏览器不支持视频播放。
      </video>
    {% endfor %}
  </div>
{% endif %}

还可以通过product-video-wrap类自定义视频容器的样式(比如间距、边框、阴影等),让视频更贴合页面风格。

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:03:27