[metafields] How to add product url for product reference metafields

I want to develop other product recommendation areas in product page with Shopify native metafields. With below code, it displays each product image but when I click the image, it doesn’t lead to each product page url and stays with same product url.

Could you advise me how I can add product reference url to metafields? Thank you.

Other product recommendations

Hey mate!

Love the use of the in-built metafields. IMO they are one of the most powerful additions to Shopify in a long time!

What the metafield returns is a reference to the product, not the product object. To get the it, you need to use the global all_products array to return the required object, and then access the url and image. For your use it would be something like:

{% assign product_rec_1 = all_products[product.metafields.custom.other-product2] %}
{% assign product_rec_1_url = product_rec_1.url %}
{% assign product_rec_1_image = product_rec_1.featured_image %}

Hey Glenn!Thank you very much for your kind advice. I revised the code on below and the issue is solved :slightly_smiling_face:

<div class="product-other-reco__inner">

{% assign product_rec_1 = all_products[product.metafields.custom.other-product1] %}

{% assign product_rec_1_url = product_rec_1.url %}

{% assign product_rec_1_image = product_rec_1.featured_image %}

{% assign product_rec_2 = all_products[product.metafields.custom.other-product2] %}

{% assign product_rec_2_url = product_rec_2.url %}

{% assign product_rec_2_image = product_rec_2.featured_image %}

<a href="{{ product_rec_1_url }}">

<img class="product-other-reco__image" src="{{ product_rec_1_image | img_url:"original"}}" alt="">

</a>

<a href="{{ product_rec_2_url }}">

<img class="product-other-reco__image" src="{{ product_rec_2_image | img_url:"original"}}" alt="">

</a>

</div>

Hello @momomoPeach ,

Here is a solution that you may like.

When you select a Product type, Metafield then you also have to use the “all_products” array to return the product object.

The “all_products” array can be used throughout all web pages to return the product object.

If you want to show a product URL, image, or title through a metafield, then you have to use the “all_products” array.

Please refer to the below code to add the product reference URL to metafields-

{% assign rec_product = all_products[product.metafields.custom.other-product1] %}

{% assign rec_product_title = rec_product.title %}

{% assign rec_product_url = rec_product.url %}

{% assign rec_product_image = rec_product.featured_image %}

Hope it helps. Please connect with us if you need any further assistance.

Regards,

CedCommerce

No worries! Glad I could help :grin:

Happy coding!