Related products available on all pages
Related products available on all pages
Jan 5, 2023 12:00 AM (3 months ago)

# Related products available on all pages

In magento, there is no out of the box related products that is available across all pages. You can see it just on product page. So I decided to play around with this, and make it available everywhere. Requirements that I set for this where simple:

  • when product is added to minicart, it would check if that product has any related products set, and list them in block that is easily moved around page.
  • it will show just the image, name and add to cart for related product

Implementation:

  • Creating UI component that will list all related products
  • If product in cart has related products set, it will display list in separate block

  • Products are fetched with graphQL, where id is SKU of products in cart
const query = `{
              products(filter: { sku: { in: ${id} } }) {
                items {
                  id
                  name
                  related_products {
                    id
                    sku
                    stock_status
                    url_key
                    name
                     small_image {
                        url
                    },
                  }
                }
              }
            } `;
  • related items are then rendered in template
<!-- ko foreach: items -->
    <!-- ko if: $data.related_products.length > 0 -->
    <h3 class="related-parent">Related products for:</h3>
    <h2 data-bind="text: name"></h2>
    <div class="wrapp-el">
    <!-- ko foreach: $data.related_products -->
        <div class="related-wrapper">
            <img data-bind="attr: {src: small_image.url }">
            <a data-bind="attr: {href: '/' + $data.url_key + '.html' }">
            <span data-bind="text: $data.name"></span>
            </a>
            <button class="add-related-to-cart" data-bind="attr: {'data-product-id' :$data.id }">Add to cart</button>
        </div>
    <!-- /ko -->
</div>
<!-- /ko -->
<!-- /ko -->

Full code can be checked here (opens new window)