Example code snippets

Here are some example code snippets to help you get started writing your own.

Hide out-of-stock products on POS

{% if product.available %}
  {% assign product.visibility = 'global' %}
{% else %}
  {% assign product.visibility = 'web' %}
{% endif %}

Set a metafield from a prefixed-tag

In this example, a product with the tag "Condition_Used" would have the custom.condition metafield set to "Used"

{% assign value = product.tags | tag_suffix: "Condition_" %}
{% if value %}
  {% assign product.metafields.custom.condition.value = value %}
{% endif %}

Set a metafield to an option value

{% assign variant = product.variants[0] %}
{% assign product.metafields.custom.brand.value = variant.option1 %}

Display an 'On-Sale' tag for products on sale

{% assign has_variant_on_sale = false %}

{% for variant in product.variants %}
  {% if variant.compare_at_price and variant.price < variant.compare_at_price %}
    {% assign has_variant_on_sale = true %}
  {% endif %}
{% endfor %}

{% if has_variant_on_sale %}
  {% assign product.tags = product.tags | add_tag: "On-Sale" %}
{% else %}
  {% assign product.tags = product.tags | remove_tag: "On-Sale" %}
{% endif %}

Set products with no sellable inventory to 'draft'

{% if product.available == false and product.status == 'active' %}
  {% assign product.status = 'draft' %}
{% endif %}

Set the cost of a product based on the vendor

If a product is from vendor1 , the cost will be set to 50% of the price. If it's from vendor2 , it will be set to 60% of the price.

{% capture vendor_percentage_text %}
{
    "vendor1": 0.5,
    "vendor2": 0.6,
    "vendor3": 0.7
}
{% endcapture %}


{% assign vendor_percentages = vendor_percentage_text | parse_json %}
{% for vendor_percentage in vendor_percentages %}
  {% assign vendor = vendor_percentage[0] %}
  {% assign percentage = vendor_percentage[1] %}

  {% if product.vendor == vendor %}
    {% for variant in product.variants %}
      {% assign variant.cost = variant.price | times: percentage %}
    {% endfor %}
  {% endif %}
{% endfor %}

Set Search Boosts from a metafield

If you want content from a metafield to be found by the Shopify Search & Discovery app you can use the following code snippet. It will copy each word from a metafield into the search boosts for that product.

{% assign boosts = product.metafields.shopify--discovery--product_search_boost.queries.value %}

{% # Add each individual word to search boost %}
{% assign words = product.metafields.custom.subtitle.value|split:" "  %}
{% for word in words %}
  Adding {{ word }}
  {% assign boosts = boosts|add_list:word %}
{% endfor %}
{% assign boosts = boosts| slice: 0,10 %}
{% assign product.metafields.shopify--discovery--product_search_boost.queries.value = boosts|json %}
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us