Acessing metaobject data from product metafield

I have a metaobject called “color” with these fields:

color.name (single text)

color.hexcode (color)

color.image (file)

I created a product metafield called product.metafields.custom.color_filter_swatch that has a content type set as the “color” metaobject and multiple entries.

From my product page I want to access the hexcolor values that the product has associated with it through the color_filter_swatch metafield (that points to the color metaobject). However I cannot find the correct syntax.

I tried debugging it by displaying liquid variables in the html and this input:

          {% if product.metafields.custom.color_filter_swatch != blank %}
            <p>Metafield is not blank.</p>
            {% assign color_metaobjects = product.metafields.custom.color_filter_swatch.value %}
            <p>Color Metaobjects: {{ color_metaobjects | json }}</p>
            <p>[0]: {{ color_metaobjects[0] | json }}</p>
            <p>size: {{ color_metaobjects | size }}</p>
            <p>color_filter_swatch size: {{ product.metafields.custom.color_filter_swatch | size }}</p>
          {% else %}
            <p>No color swatches assigned.</p>
          {% endif %}

is giving me this output:

Metafield is not blank.

Color Metaobjects: [{“hexcode”:“#be0000”,“name”:“Red”},{“hexcode”:“#737373”,“name”:“Grey”},{“hexcode”:“#ffffff”,“name”:“White”},{“hexcode”:“#000000”,“name”:“Black”}]

size: 0

color_filter_swatch size: 0

Which I find rather weird. The color_metaobjects variable is displayed as an array of objects, but when I try to access its elements it behaves as if it wasn’t an array ( color_metaobjects0 is null and color_metaobjects.size is 0). I also tried to access it using color_metaobjects0.value but it’s also null.

What could I be missing here?

Thanks in advance, any help would be very much appreciated.

Hi @felipelf00

Please try to update like below:

{% if product.metafields.custom.color_filter_swatch != blank %}
  

Metafield is not blank

  {% assign color_metaobjects = product.metafields.custom.color_filter_swatch.value %}
  {% for color_metaobject in color_metaobjects %}
    

Name: {{ color_metaobject.name }}

    

Hexcode: {{ color_metaobject.hexcode }}

    

Image: 

  {% endfor %}
{% else %}
  

No color swatches assigned.

{% endif %}

Hope this helps!

1 Like

Thanks for your reply. I ended up finding a solution, but it’s similar to what you suggested.

Basically to access a value that is in a list, you must iterate throught that list (syntax such as color_metaobject[0] does not work).

This worked for me:

            {% for item in product.metafields.custom.color_filter_swatch.value %}
              <p>item.hexcode: {{ item.hexcode }}</p>
            {% endfor %}

This video also helped me clarify the different syntaxes for each type of metafield:

https://www.youtube.com/watch?v=eQHt2xil3Js