Magento 2 Related Products – How to Display Swatches

configurable-swatchesmagento-2.1related-products

I added related products list in product details page.
I see there all related products list are display but now i need to display swatches in this list. How can it possible for related products list.

If any one know please give me answers.

Best Answer

In app/design/frontend/MyCompany/mytheme/Magento_Catalog/templates/product/list/items.phtml please add below code :

<?php if($_item->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){

 $swatchBlock = $this->getLayout()->createBlock("Magento\Swatches\Block\Product\Renderer\Listing\Configurable")->setTemplate("Magento_Swatches::product/listing/renderer.phtml");
   echo $swatchBlock->setProduct($_item)->toHtml();                           
} ?>

And also in

app/design/frontend/MyCompany/mytheme/Magento_Swatches/layout/catalog_product_view.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
    <css src="Magento_Swatches::css/swatches.css"/>
  </head>

</page>
Related Topic