Custom Text Field for Shopify Cart and Products


Shopify’s cart object has a few places that allow us to customize customer orders with custom text. These include the cart ‘attributes’, ‘notes’, and individual line item ‘properties’.

Cart attributes are used to store custom information that applies to the entire cart, rather than individual items. This could include things like custom instructions, delivery preferences, or any other metadata that is relevant to the whole order.

Cart notes are typically used to collect a single note from the customer about the order. This note could contain special instructions, gift messages, or other details the customer wants to communicate to the store.

Line item properties are used to store custom information for specific products in the cart. This is useful for collecting customization details for individual products, such as engraving text, color preferences, or personalized messages.

Today I am going to walk through the process of adding a text field to add a cart attribute to your theme. The principles here are very similar regardless of which type of text field you are trying to add to your cart. Note I am using the Dawn theme in this tutorial. Let’s get started!

Code: https://github.com/ndrishinski/blogs/commit/b2fca7fd0562136958a41e72e8c1f359b6cba72f

Prefer Video?

Enjoy, otherwise read on!

Create a Local Theme Block

We are going to add this as a block to a section so a merchant can easily add, remove or customize this text box from the customizer. So let’s open up the ‘sections’ directory and open ‘main-product.liquid’. If we scroll down to the ‘schema’ section we can add our block under the ‘blocks’ like so:

{% schema %}
{
  "name": "t:sections.main-product.name",
  "tag": "section",
  "class": "section",
  "blocks": [
    {
      "type": "@app"
    },
    ADD THIS BLOCK BELOW
    {
      "type": "cart_attribute",
      "name": "Cart attribute",
      "limit": 1,
      "settings": [
        {
          "type": "text",
          "id": "label",
          "default": "Would you like to personalize this gift?",
          "label": "Verbage for the text box label"
        }
      ]
    },
...

Now if we save this file we should see this block as an option in the customizer. But first let’s add some HTML/Liquid above so we can render our UI. We need to find the place we want to insert out text box in the UI. In Dawn, still in the ‘main-product.liquid’ file I am going to paste the following code in above the popup block:

              </div>
              {%- when 'cart_attribute' -%}
                  <div id="cart_attribute">
                    <label for="cart_attribute">
                      {{ block.settings.label }}
                      <input type="text" id="cart_attribute" placeholder="Recipient's Name" />
                    </label>
                  </div>
              {%- when 'popup' -%}
              ...

Next in this file, I want to add a minor style adjustment in-between the style tags like so:

...
#cart_attribute input {
      height: 47px;
      text-align: center;
      font-size: 14px;
      margin-top: 7px;
    }
{%- endstyle -%}

Lastly in this file, we need to add some JavaScript to perform the Ajax Cart API request. So at the bottom of the HTML I am going to add a script like so:

...
</div>
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        function addCartAttribute(attributeKey, attributeValue) {
          fetch('/cart/update.js', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify({
              attributes: {
                [attributeKey]: attributeValue
              }
            })
          })
          .then(response => response.json())
          .then(data => {
            console.log('Cart item properties updated:', data);
          })
          .catch((error) => {
            console.error('Error:', error);
          });
        }
        
        document.querySelector('.product-form__submit').addEventListener('click', function() {
          // target input for value
          const value = document.querySelector('#cart_attribute input').value
          if (!!value) {
            addCartAttribute('Gift-To', value)
          }
        })
      })
    </script>

**Note that I am targeting the class ‘product-form__submit’ to listen to the ‘Add To Cart’ button click’ Your theme may have a different class name or id that you need to swap instead. To check, right click on your add to cart button and click ‘Inspect’. Note the values in ‘class=”‘.

Add Block in Customizer

Now that we have updated our ‘main-product.liquid’ section to include our new block we can add it in our theme customizer. If I navigate to the ‘Default Product’ template in the customizer, I can click ‘Add block’ under the Main Product section.

After adding you can see the option to customize wording:

Conclusion

After saving all of our changes, we should have a fully functioning text field that adds text to ‘Cart Attributes’ in an order. The value is available in the dashboard as well as order exports. I hope this has been helpful and if you’re interested in learning more about Shopify development please fill out this form.