Fetch and Display Recommended Products Using Shopify AJAX API

Fetch and Display Recommended Products Using Shopify AJAX API

Shopify provides an endpoint that allows you to fetch recommended products dynamically based on a product’s ID.

1. Add a Container for Recommended Products

Place this inside your product.liquid or a custom section:

<div id="recommended-products">
    <h2>Recommended Products</h2>
    <div class="recommendation-list"></div>
</div>

2. JavaScript to Fetch Recommended Products

Add this AJAX script inside theme.js or in a <script> tag:

document.addEventListener("DOMContentLoaded", function () {
    let productId = document.querySelector("meta[property='og:url']").content.split("/").pop();
    let recommendationUrl = `/recommendations/products.json?product_id=${productId}&limit=4`;

    fetch(recommendationUrl)
        .then(response => response.json())
        .then(data => {
            let recommendationContainer = document.querySelector(".recommendation-list");
            recommendationContainer.innerHTML = ""; // Clear existing content

            if (data.products.length > 0) {
                data.products.forEach(product => {
                    recommendationContainer.innerHTML += `
                        <div class="recommended-product">
                            <a href="${product.url}">
                                <img src="${product.featured_image}" alt="${product.title}">
                                <p>${product.title}</p>
                                <p>Price: ${Shopify.formatMoney(product.price)}</p>
                            </a>
                        </div>`;
                });
            } else {
                recommendationContainer.innerHTML = "<p>No recommendations available.</p>";
            }
        })
        .catch(error => console.error("Error fetching recommendations:", error));
});

3. Explanation of the Code

  • Finds the product ID from the current page URL.
  • Fetches recommended products from /recommendations/products.json?product_id={id}&limit=4.
  • Loops through the response and dynamically creates product cards.
  • Handles errors gracefully in case the API fails.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top