Linking Variant Metafields in a Custom HTML Block

Hi! I’m trying to link to 3rd party web pages from my Shopify product pages, via metafields and a custom button. I got this to work perfectly with product metafields, and then realized I wanted specific links to each variant, and now the code I was using no longer works. The code I used in a custom HTML block on my product page is as follows (the top part is to create the button):

.custom-button-2 { background-color: #127719; color: white; padding: 14px 150px; width: 100%; border: 2px; border-radius: 5px; cursor: pointer; font-size: 18px; font-weight: bold; font-family: poppins;

buy now on amazon

It links to the first variants custom link, but when choosing the second variant, the link is the same as the first. Picture below and website link is https://repelwell.com/ Thank you!

As you have already guessed this will need variant metafields rather than product. And Shopify by default populates the first variant on the frontend with its value only the first variant gets the metafield value.

For variant specific linking there’s slightly more work. So you have to listen for clicks events on the variants and according to that set the button link to that variant metafield.

So set up variant metafields and you will need a bit of js code.

Best

Thanks for the reply! I do have the variant metafields set up and linked to the product page - but that’s where it stops working. It just links to the first variant link. Do you know the js code that has to be added? Sounds like that’s what I’m missing.

Because it requires outputting the variant value with liquid I will require Collab access to your store, if it was just js I could have tried it on my end with just the url.

What I have in mind now is to add a data field on each variant selector with the url and on the click of that variant get the url and link to the button. It will require liquid to add to the variant buttons

Hi! This didn’t quite work. See below..

Shopify does not automatically update custom HTML when a variant changes. Product metafields work because they’re static, but variant metafields require JavaScript.

The fix is to expose variant metafields in Liquid and update the button dynamically when the selected variant changes. Once implemented, each variant will correctly link to its own external page.