Add to Cart Button

Integrating an Add to Cart (ATC) button within product cards in Shopify enhances user experience by allowing customers to quickly add items to their shopping carts.

Follow these concise steps to seamlessly integrate the ATC button into your Findify-powered Shopify store's product cards.

Integration Steps

Step 1: Create a New Asset

  1. Navigate to Theme → Edit Code → Assets in your Shopify admin panel.

  2. Add a new asset and name it accordingly (e.g., customAddToCart.js).

  3. Paste the provided JavaScript code into the newly created asset.

function addToCart(id, selectedVariantId) {

  const formData = {
    items: [{
      id: selectedVariantId,
      quantity: 1
    }]
  };

  const apiUrl = window.Shopify.routes.root + 'cart/add.js';

  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
  };

  fetch(apiUrl, requestOptions)
	.then(res => handleResponse(res, id, selectedVariantId))
    .catch(handleError)
}

function handleResponse(res, id, selectedVariantId) {
  return res.json().then(data => {
    if(data?.items) {
      alert('Item added to cart');

      findify.core.analytics.sendEvent('click-item',
        {
            rid: findify.grid.state.meta.rid,
            item_id: id,
            variant_item_id: selectedVariantId
        },
        false
      )
    }
    else {
      const errorDescription = data?.description || 'Unexpected Error';
      alert(errorDescription);
    }
  })
}

function handleError(error) {
  const errorDescription = error?.description || 'Unexpected Error';
  alert(errorDescription);
}

Step 2: Include Script in Theme Layout

  1. Open the theme.liquid file in your Shopify theme editor.

  2. Paste the following script immediately after the <head> tag to include the custom JavaScript file.

<head>
	...
	<script src="{{ 'yourAssetName.js' | asset_url }}" defer="defer"></script>
</head>

Step 3: Add Button to Product Card

  1. Locate the findify-product.liquid file in your Shopify theme editor.

  2. Insert the following HTML code snippet within the product card section to add the ATC button.

<div>
	<a href={{ product_url }}>
		// ... other code 
	</a>
	<button onclick="addToCart({{ id }}, {{  selected_variant_id }})" >
		Add to cart
	</button>
</div>

Conclusion

By following these simple steps, you can seamlessly integrate an Add to Cart button into product cards within your Shopify store. Empower your customers to make quick purchase decisions and enhance their shopping experience with this intuitive feature.

For further assistance or inquiries, feel free to contact us on [email protected].