Quantity in cart for donations on shopify

I recently had a need to set up donation functionality on a Shopify web store.  Shopify provides a great method for adding donations to the shopping cart, but I found one aspect of functionality lacking.

Because the donations are implemented as an arbitrary number of a 1 cent donation item added to the shopping cart, if the user gets back to a page where the number of items in the shopping cart is displayed (like in a widget in the header), the number shown will be the number of items in the cart, plus the number of cents being donated.  Our desired behavior was to have a donation represented in this total as a single item, regardless of the amount.

The code in our template for showing the number of items in the cart looked like this to begin with:

{% if cart.item_count == 0 %}
Your cart is empty
{% else %}
{{ cart.item_count }} item{% if cart.item_count != 1 %}s{% endif %}
{% endif %}

Here is the code I came up with to correct the number:

{% if cart.item_count == 0 %}
Your cart is empty
{% else %}
{% assign donating = 0 %}
{% for item in cart.items %}
{% if item.title contains ‘Donation’ %}
{% assign donating = item.quantity %}
{% endif %}
{% endfor %}
{{cart.item_count | minus: donating | plus: 1 }} item{% if cart.item_count != 1 %}s{% endif %}
{% endif %}

The one case where this breaks down a bit is where a user might have a donation of more than one cent in the cart, with no products, and the text will still pluralize item, showing “1 Items” in cart.  While this is also fixable, it’s a case we’re not worried about because we don’t anticipate many users will donate without something else in the cart.

I’m really enjoying working with Shopify as a platform.  There are some limitations to the templating engine (Liquid), but they are understandable from a security standpoint for a hosted, reliable provider.

Leave a Reply