如何在Shopify博客添加关联商品?含无插件及代码实现指南
在Shopify博客页面添加关联商品(无插件实现)
首先明确:完全可以在Shopify博客页面添加并展示关联商品,无需第三方插件,通过自定义Liquid代码就能实现。
一、分步操作指南
准备工作:获取商品Handle
- 登录Shopify后台,进入「产品」页面
- 找到目标关联商品,进入详情页后,复制浏览器地址栏末尾的字符串(比如
wireless-headphones),这就是商品的handle,后续代码会用到
方法1:单篇博客插入代码(仅当前文章生效)
- 进入「在线商店」→「博客文章」,打开要编辑的文章
- 切换到「HTML」编辑模式(避开可视化编辑器)
- 插入以下代码,将
your-product-handle替换为你复制的商品handle:
<div class="blog-related-product"> {% assign related_product = all_products['your-product-handle'] %} {% if related_product %} <h3>推荐商品</h3> <a href="{{ related_product.url }}"> <img src="{{ related_product.featured_image | img_url: 'medium' }}" alt="{{ related_product.title }}"> <h4>{{ related_product.title }}</h4> <p>{{ related_product.price | money }}</p> </a> <form action="/cart/add" method="post"> <input type="hidden" name="id" value="{{ related_product.variants.first.id }}"> <button type="submit" class="btn">加入购物车</button> </form> {% endif %} </div>
- 切换回可视化编辑器预览效果,确认无误后保存文章
方法2:修改主题模板(所有博客自动支持关联商品)
如果需要批量给博客文章添加关联商品,可修改主题模板:
- 进入「在线商店」→「主题」→ 点击当前主题的「操作」→「编辑代码」
- 在左侧文件列表中找到并打开
article.liquid或sections/article-template.liquid(取决于主题结构) - 找到要放置关联商品的位置(比如文章内容末尾、侧边栏),插入以下代码:
{% if article.tags contains 'related-product' %} {% assign product_handle = article.tags | split: 'related-product-' | last %} {% assign related_product = all_products[product_handle] %} {% if related_product %} <div class="blog-related-product"> <h3>你可能喜欢</h3> <div class="product-card"> <a href="{{ related_product.url }}"> <img src="{{ related_product.featured_image | img_url: 'large' }}" alt="{{ related_product.title }}"> <h4>{{ related_product.title }}</h4> <span>{{ related_product.price | money }}</span> </a> <button onclick="Shopify.addItem('{{ related_product.variants.first.id }}', 1)" class="add-to-cart-btn">加入购物车</button> </div> </div> {% endif %} {% endif %}
- 保存模板后,编辑博客文章时添加标签
related-product-你的商品handle(比如related-product-wireless-headphones),该文章就会自动展示对应的关联商品
二、自定义代码的样式调整
如果展示样式不符合店铺风格,可在主题的base.css或theme.css文件中添加自定义CSS,示例:
.blog-related-product { border: 1px solid #eee; padding: 20px; margin: 30px 0; text-align: center; } .blog-related-product img { max-width: 200px; margin: 0 auto; } .blog-related-product .btn { background-color: #000; color: #fff; padding: 10px 20px; border: none; cursor: pointer; }
三、简单添加的快捷方法
部分主题支持「嵌入代码」块,可直接用这个方式快速添加:
- 编辑博客文章时,点击「添加块」→ 选择「嵌入代码」
- 粘贴替换好handle的Liquid代码,保存即可
内容的提问来源于stack exchange,提问作者DongFuCamera
相关产品推荐
相关产品推荐

