How to generate all skus for a product in a single line

Tourist
4 0 1

Hi,

 

I've been trying to get a string of SKU's in a line for each our products like the below:

sku1,sku2,sku3,sku4

 

The reason I would like to do this is that we're implementing TrustPilot Product Reviews in to our webiste and their review code requires all the skus for the product in order to pull the relevant reviews.

 

I can pull the first sku in using: {{ product.variants.first.sku }} which loads only the reviews for that sku. I've copied the code below which I am using to generate the review ratings also attached is the result. The issue is that it only loads the review data for the first sku which only has 5 reviews but the product actually has 93 across all of the skus.

 

Someone has mentions that is could be done using Json? I must admit I am a novice when it comes to coding.

 

I'm hoping someone can help me find a solution.

 

Thanks, Tom

 

<!-- TrustBox widget - Product Mini MultiSource --> <div class="trustpilot-widget" data-locale="en-GB" data-template-id="XXXX" data-businessunit-id="XXXX" data-style-height="24px" data-style-width="100%" data-theme="light" data-sku="{{ product.variants.first.sku }}"> <a href="https://uk.trustpilot.com/review/gumbies.co.uk" target="_blank">Trustpilot</a> </div> <!-- End TrustBox widget -->

0 Likes
Shopify Partner
1843 170 534

Hi,

 

So if you need a comma separated list of your product variants' SKUs, you can do something like

  {%- capture variant_skus -%}
    {%- for variant in product.variants -%}
      {{- variant.sku -}}{%- if forloop.last == false -%},{%- endif -%}
    {%- endfor -%}
  {%- endcapture -%}
  
  {{ variant_skus }}

You'd capture the SKUs before your TrustBox integration snippet and then simply provide the {{ variant_skus }} to it.

 

In case you'd need an array of variant SKUs you can also add following to above

  {%- assign skus_array = variant_skus | split: ',' -%}

And work with that array as you'd normally do in Liquid.

 

Hope this helps!

I turn coffee in to code - since 1998
2 Likes
Tourist
4 0 1

Thank you so much! Worked a treat! 

1 Like
Shopify Partner
1353 20 187

Array map can also be handy in this case: https://help.shopify.com/en/themes/liquid/filters/array-filters#map

 

{{ product.variants | map: 'sku' }}

 

wish we had more Array methods :(

https://sections.design tips, tricks & Shopify sections
1 Like
Highlighted
Shopify Partner
1843 170 534

Ah, @Mircea_Piturca much more elegant. Forgot about the map. Should be the correct answer!

I turn coffee in to code - since 1998
0 Likes
Shopify Partner
1353 20 187

@KarlOffenberger a loop can give you more freedom.

The map will just output the Array... both methods are useful depending on the case IMHO

 

https://sections.design tips, tricks & Shopify sections
0 Likes