Any way to access reverse references using Liquid?

Our site is both an artist’s portfolio/gallery and store. Each piece artwork is stored as a metadata object. They may or may not have prints/products available. Each print/product has a reference to the artwork (metadata object) that it is based on.

I would like to display on the artwork metadata object pages a list of all prints/products based on that piece of art. Is there a way, in liquid, to find all products that reference the metadata object without looping through the entire catalog?

No, there isn’t a built-in way in Shopify Liquid to directly filter all products by a metafield referencing another object. However, you can achieve this functionality with a two-step approach:

1.Access the artwork’s unique identifier: Within your Liquid code, you should be able to access the artwork metadata object’s unique identifier. This could be an ID number or handle.

2.Filter products using metafield queries: Use the product object and metafield filters to find products that have a metafield value matching the artwork’s unique identifier. Here’s an example:

Code snippet

{% assign artwork_id = product.metafields.art_reference.value %} {% assign related_products = products | where: ‘metafields.art_reference.value’, artwork_id %}

{% if related_products.size > 0 %}

Prints based on {{ product.title }}

{% else %}

No prints available for this artwork.

{% endif %}

Explanation:

We assign the artwork’s unique identifier from the art_reference metafield (replace with your actual metafield name) to the artwork_id variable.
We use the products object and filter it using the where clause. This clause filters products based on a specific condition. In this case, we check if the art_reference metafield’s value matches the artwork_id.
We then check if any products were found using related_products.size. If there are results, we loop through them and display the product title and link.

Important points:

This approach assumes you have a single metafield on the product referencing the artwork metadata object.
Make sure to replace art_reference with the actual name of your metafield storing the artwork reference.

This method allows you to filter products based on the artwork’s metafield without iterating through the entire product catalog, improving efficiency.

Sorry, marked this as the solution - but there is a problem. I’m trying to do this from the metadata object (artwork) page. The code would need to be more like this:

{% assign related_products = collections[‘all’].products | where: ‘metafields.art_reference.value’, metaobject %}

{% if related_products.size > 0 %}

Prints based on {{ metaobject.title }}

{% else %}

No prints available for this artwork.

{% endif %}

Sadly, this does not seem to work…