So recently I was looking to add recommended product upsells to my cart, and after writing a few lines of code I got stuck. I managed to get the upsells to show, as well as finding a script that adds the item directly to the cart drawer:
{%- assign current_variant = product.selected_or_first_available_variant -%}
But the issue with this is that you cannot change the variant, so I also added this piece of code:
And it works great, the select shows all the variants, when I use inspector I can see all the variant id’s, but the only problem is I cannot get the current_variant to update according to the option selected in the dropdown. The current variant always stays as the first available variant id, so I’m looking for some help on how to write a script that will update the current variant for me, and replace it according to the variant id thats attached to the selected option from the dropdown. Any help is appreciated, thanks a lot :))
So after some more brainstorming I figured out the solution. Here is the process that you have to take, or at least the one I took to make this work:
-
Add a select dropdown, with all your variants as options, and attach variant.id to those options
-
Add an input before your variant
-
Write a script that will make sure the variant.id of the select option will be the value of the input
-
Write a script that will make your buttons on click {{current_variant.id}} match the inputs value
Some things worth mentioning:
- If you’re displaying multiple products you have to add a forloop.index to your select dropdown, product wrapper, input, and button.
Below I attached how my cart drawer code looked like in the end:
{% if request.locale.iso_code == 'nl' %}
{%- if recommendations.performed? and recommendations.products_count > 0 -%}
## Maak je bestelling af
{% endif %}
{%- for product in recommendations.products -%}
{{ product.title }}
{% if product.compare_at_price %}
{{ product.compare_at_price | money }}
{% endif %}
{{ product.price | money }}
{% assign current_variant = product.selected_or_first_available_variant %}
{%- endfor -%}
{% endif %}
{% if settings.cart_notes_enable %}
{% endif %}
As well as the scripts:
- Script that matches option’s variant.id with the input value:
- Script that matches the input value with the button’s onclick {{current_variant.id}}
- Add to cart drawer script
As you can tell the first 2 scripts have a lot of variables, and classes which end with a 1. The reason for this is, since I’m using forloop.index I couldn’t figure out how to implement that into the script and make it work, so for my 5 products I’m displaying I just repeated the script 5 times, changing all the 1’s into 2’s, into 3’s, etc. Hopefully this helps someone in the future 
1 Like
Hi,…Can you share entire cart-drawer.liquid ? I am looking for the same solution but could not follow exactly steps you outlined…Thanks in Advance
Seems like way too much work. OMG