Ad

Shopify: I Need A Link To A Product To Place In A Template File

- 1 answer

I need to add a link to a product in a template file. I was thinking of having in the schema a field the admin can edit. This field should be a select with all the products or a simple text field with autocomplete.

Is this possible? Or should I just have a simple text field and let admin copy/paste the actual product url in there?

Thanks.

Ad

Answer

If you're creating settings in the theme, section or section-block, use 'product' as the field type. By choosing 'product' as the type, the merchant will be given a product-selector complete with a search box in the theme settings. For all available field types, see https://help.shopify.com/en/themes/development/theme-editor/settings-schema#special-input-setting-types

When you access the setting, you will be given just the handle of the product selected by the merchant. If you named your setting 'user_product', you would translate that into an actual product object in Liquid using:

{% assign user_product = all_products[settings.user_product] %}

Since you have access to all of the attributes of the linked product, you can then place the URL of the selected product normally. Eg:

<a target="_blank" rel="nofollow noreferrer" href="{{ user_product.url }}">{{ user_product.title }}</a>

Hope this helps!

Ad
source: stackoverflow.com
Ad