Custom cart JSON API for more information like compare_at_price for items in cart

This is an advanced tutorial and proceed only if understand the risks.

Shopify’s Ajax API for cart is missing some fields like compare_at_price and inventory details for items in cart. And for some merchants, it is important to show those details in cart drawer.

  1. Create a new file index.ucd.liquid in templates of your Shopify Theme. Copy and pate the following code and Save:

    {%- layout none -%}
    { 
      "cart":  {{ cart | json }},
      "items": [
          {%- for item in cart.items -%}
          {
            "variant": {{ item.variant | json }},
            "product": {{ item.product | json }},
            "inventory_quantity": {{ item.variant.inventory_quantity | times: 1 }},
            "inventory_policy": {{ item.variant.inventory_policy | json }},
            "compare_at_price": {{ item.variant.compare_at_price | times: 1  }},
            "compare_at_price_formatted": {{ item.variant.compare_at_price | money | json }}
          }{%- if forloop.last != true -%},{%- endif -%}
          {%- endfor -%}
        ]
    }
    
  2. Create a new snippet file in snippets/upside-ucd-cart-api.liquid and paste the following code:

    <!-- Upsell Cart Drawer -->
    <script>
      window.addEventListener("Upside::UCD::Initialized", function(){
        upside.ucd.cart_path = '/?view=ucd';
           
        upside.ucd.filters.raw_cart.push(function(cart){
          if (upside.ucd.cart_path.includes('view=ucd')) {
            cart.cart.items = cart.cart.items.map(function(item, index){
              item = {...cart.items[index], ...item };
    
              return item;
            });
            return cart.cart;
          }
    
          return cart;
        });
      });
    </script>
    
  3. Edit theme.liquid file of your theme and add the following code right after starting <head> tag and save:

    {% include 'upside-ucd-cart-api' %}
    
  4. Use your custom variables in app’s theme templates.

  5. Test throughly.

Example:

{{#ne line_price_formatted compare_at_price_formatted}}
<span class="ucd-price-original" data-compare-at-price-html>{{{compare_at_price_formatted}}}</span>
{{/ne}}