Hi
Can anyone help me with a good solution for adding another product attached to the product via a metafield to the cart - the extra product is a packaging, so it should also calculate how many based on a number set as a metafield.
For example:
- Add product A to the cart
- Automatically add product B to the cart (attached as metafield 1 on product A): Quantity: metafield 2 on product A divided_by:Product A qty (round up to nearest whole number)
- If I remove Product A, product B should also be removed.
Should work with multiple products in the cart.
Thanks!
- Open your Shopify admin and navigate to Online Store > Themes.
- Locate your current theme and click on the “Actions” button, then select “Edit code” from the dropdown menu.
- In the left sidebar, under the “Sections” folder, find and click on the “cart-template.liquid” file.
- Scroll through the code until you find the {% for item in cart.items %} loop. This loop iterates over each item in the cart.
- Inside the loop, you can add the following code to check if the current item has a metafield for the additional product (product B) and then add it to the cart:
{% if item.product.metafields.custom.metafield_key_1 %}
{% assign extraProductQty = item.quantity | divided_by: item.product.metafields.custom.metafield_key_2 | ceil %}
{% for i in (1..extraProductQty) %}
{% assign extraProductVariant = 'Product B Variant ID' %} {# Replace with the actual variant ID of product B #}
{% assign extraProduct = all_products[extraProductVariant] %}
{% if extraProduct %}
{% endif %}
{% endfor %}
{% endif %}
Make sure to replace ‘Product B Variant ID’ with the actual variant ID of the extra product you want to add.
- Save the changes to the file.
Thanks - will it automatically add it to the cart then?
I have tried this:
{% for item in cart.items %}
{% if item.product.type != 'Fragt' %}
{%
render 'cart-item',
item: item,
show_sku: show_sku,
item_index: forloop.index,
%}
{% endif %}
{% if item.product.metafields.custom.anbrud_antal %}
{% assign attachedShippingID = item.product.metafields.custom.attached_packaging.value.id %}
{% assign extraProductQty = item.quantity | divided_by: item.product.metafields.custom.anbrud_antal | ceil %}
{% for i in (1..extraProductQty) %}
{% assign extraProductVariant = attachedShippingID %}
{% assign extraProduct = all_products[extraProductVariant] %}
{% if extraProduct %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
It is now creating the input, but I need it to be added to the cart as well.
Could you share your store URL where you implemented the above code?
droemmehave.dk (I’m trying in another copied theme)
YOu can share the preview link of that copied theme. SO I can check on that.
I am not able to see any quantity selector product which adds automatically to your cart. Does it work?
If not then could explain in detail what you need exactly?
Hi, we’ve disabled the quantity selector - is that necessary?
Is this function implemented? I have the same problem as you