Showing product recommendations on the product page using the JSON API

This tutorial describes two different ways to display product recommendations with the Shopify Ajax API: by creating product cards with JavaScript, and by creating product cards in product-template.liquid with Liquid.

Both methods include loading the recommended products that are associated with a given product by querying the /recommendations/products.json endpoint in the Shopify Ajax API. After you load the recommended products, you create product cards that can be used to display them.

To learn more about how product recommendations work, see Showing product recommendations on product pages.

Create product cards

You can create product cards for product recommendations by using either of these methods:

Option 1: Create product cards using JavaScript

This method creates the recommended product cards using JavaScript. Afterwards you need to add the recommended products container to the product template. Any visual adjustments using HTML or CSS should be added afterwards.

  1. Paste the following JavaScript code into the proper place in your theme:
  // Find the container that will hold the recommendations
  var list = document.querySelector(".product-recommendations__list");
  // Get the product id to request the product recommendations
  var productId = list.dataset.productId;
  // Create an AJAX request
  var request = new XMLHttpRequest();

  request.open(
    "GET",
    "/recommendations/products.json?product_id=" + productId + "&limit=4"
  );

  request.onload = function() {
    if (request.status === 404 || request.status === 422) {
      return hideRecommendationsSection();
    }

    var products = JSON.parse(request.response).products;

    if (products.length === 0) {
      return hideRecommendationsSection();
    }

    // Append product recommendations to the DOM.
    list.innerHTML = products.map(function(product) { return renderProduct(product) }).join("");
  };

  request.onerror = function() {
    hideRecommendationsSection();
  };

  // Send AJAX request
  request.send();

  function hideRecommendationsSection() {
    list.style.display = "none";
  }

  function renderProduct(product) {
    return [
      '<div>',
        '<a href="' + product.url + '" class="product__anchor">',
          '<img class="product__img" src="' + product.featured_image + '" alt="'+ product.title +'"/>',
          '<p class="product__title">' + product.title + '</p>',
          '<p class="product__price">' + formatMoney(product.price, window.moneyFormat) + '</p>',
        '</a>',
      '</div>'
    ].join("");
  }
  1. Open your product.liquid template file. This can be found in the Templates folder.

  2. Add the following HTML container where you want to display the recommended products:

  <div class="product-recommendations__list" data-product-id="{{ product.id }}"></div>
  1. Click Save.

  2. Add the currency formatting function to your theme.

Option 2: Create product cards in product-template.liquid

This method places the code for the product cards within the product-template page, and then uses the API call to fill in the product information.

  1. Open your product.liquid template file. This can be found in the Templates folder.

  2. Add a container to hold the recommended products section and add the markup for a product card inside:

      <div class="product-recommendations__list" data-product-id="{{ product.id }}">
        <div class="product-recommendation__card">
          <a href="#" class="product__anchor">
            <img class="product__img" src="" alt="" />
            <p class="product__title"></p>
            <p class="product__price"></p>
          </a>
        </div>
      </div>

    The above code is missing the href, image, title and price for products. These are added using JavaScript.

  3. Paste the following JavaScript code into the proper place in your theme:

  // Find the container that will hold the recommendations
  var list = document.querySelector(".product-recommendations__list");
  // Get the product id to request the product recommendations
  var productId = list.dataset.productId;
  // Create an AJAX request
  var request = new XMLHttpRequest();

  request.open(
    "GET",
    "/recommendations/products.json?product_id=" + productId + "&limit=4"
  );

  request.onload = function() {
    if (request.status === 404 || request.status === 422) {
      return hideRecommendationsSection();
    }

    var products = JSON.parse(request.response).products;

    if (products.length === 0) {
      return hideRecommendationsSection();
    }

    // Select the empty product card that was rendered by liquid
    var productCardTemplate = document.querySelector(
      ".product-recommendation__card"
    );
    var fragment = document.createDocumentFragment(); // Create a fragment that will hold the product cards
    products.forEach(function(product) {
      var template = productCardTemplate.cloneNode(true);
      template.querySelector(".product__anchor").href = product.url;
      template.querySelector(".product__img").src = product.featured_image;
      template.querySelector(".product__img").alt = product.title;
      template.querySelector(".product__title").innerText = product.title;
      template.querySelector(".product__price").innerText = formatMoney(
        // To see what this function does check the Currency Formatting section
        product.price,
        window.moneyFormat
      );
      fragment.appendChild(template);
    });
    list.removeChild(productCardTemplate); // Delete the template output by liquid
    list.appendChild(fragment); // Display recommendations
  };

  request.onerror = function() {
    hideRecommendationsSection();
  };

  // Send AJAX request
  request.send();

  function hideRecommendationsSection() {
    list.style.display = "none";
  }
  1. Click Save.

  2. Add the currency formatting function to your theme.

Update the currency format

By default, the price property for each recommended product is given in cents. To display the price with the correct currency symbol and decimal places, follow these steps.

Step 1: Get the currency formatting function

The way to do this depends on how you manage your JavaScript modules:

  • If you use NPM or Yarn to manage your JavaScript modules, then install the @shopify/theme-currency npm package. You can do this by running the following command:

    `yarn add @shopify/theme-currency` or `npm i @shopify/theme-currency`
  • If you don’t use NPM or Yarn, then copy this code from the Shopify Github repository and paste it in the file where you render the recommended products.

Step 2: Output the currency format from liquid

Add code to the theme.liquid file to format the currency with the proper symbols and decimals:

  1. In the Layout directory, open the theme.liquid file.
  2. Add the following code:

    <script>
      window.moneyFormat = {{ shop.money_format | json }};
    </script>
  3. Click Save.

Step 3: Format the product price

After loading the recommended products from the API, use the currency formatting function added in step 1 and the money format from step 2 to get the formatted currency. For example:

  const formattedPrice = formatMoney(recommendedProduct.price, window.moneyFormat);
  console.log(formattedPrice); // This will output the currency with the proper symbol. Example: 10$
  // Use the formattedPrice to render it on the DOM

Tracking conversions for product recommendations

To track the conversion rate of your recommendations, you need to assign the product.url property to the href attribute for each anchor tag that links to the page of a recommended product. This property contains information that lets you build a conversion funnel that can be tracked by using reports in Shopify.

To learn more about product recommendation reports, see Product recommendation conversion over time.

Example:

  <a href="${recommendedProduct.url}">This is a link to a recommended product page</a>

Ready to start selling with Shopify?

Try it free