Skip to content

How set limit of product’s swatches on category listing page in magento246

How to set limit of product’s swatches on category listing page. I have to show 5 swatches of the product on category listing page.
I have tried below code but that’s code working only 5 swatches of product and less than 5 swatches of products, Not working with greater than 5 Swatches of products.

Code is …

app/design/frontend/Vendor/theme/Magento_Swatches/templates/product/listing/renderer.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

use MagentoCatalogModelProduct;
use MagentoSwatchesBlockProductRendererListingConfigurable;
use MagentoSwatchesViewModelProductRendererConfigurable as ConfigurableViewModel;

/** @var Configurable $block */
/** @var Product $product */
$product = $block->getProduct()
?>
<?php if ($product && $product->isAvailable()): ?>
    <?php $productId = $product->getId() ?>
    <?php /** @var ConfigurableViewModel $configurableViewModel */ ?>
    <?php $configurableViewModel = $block->getConfigurableViewModel() ?>
    <div class="swatch-opt-<?= $block->escapeHtmlAttr($productId) ?>"
         data-role="swatch-option-<?= $block->escapeHtmlAttr($productId) ?>"></div>

    <script type="text/x-magento-init">
        {
            "[data-role=swatch-option-<?= $block->escapeJs($productId) ?>]": {
                "Magento_Swatches/js/swatch-renderer": {
                    "selectorProduct": ".product-item-details",
                    "onlySwatches": true,
                    "enableControlLabel": false,
                    "numberToShow":5,
                    "jsonConfig": <?= /* @noEscape */ $block->getJsonConfig() ?>,
                    "jsonSwatchConfig": <?= /* @noEscape */ $block->getJsonSwatchConfig() ?>,
                    "mediaCallback": "<?= $block->escapeJs($block->escapeUrl($block->getMediaCallback())) ?>",
                    "jsonSwatchImageSizeConfig": <?= /* @noEscape */ $block->getJsonSwatchSizeConfig() ?>,
                    "showTooltip": <?= $block->escapeJs($configurableViewModel->getShowSwatchTooltip()) ?>
                }
            }
        }
    </script>

    <script type="text/x-magento-init">
        {
            "[data-role=priceBox][data-price-box=product-id-<?= $block->escapeJs($productId) ?>]": {
                "priceBox": {
                    "priceConfig": {
                        "priceFormat": <?= /* @noEscape */ $block->getPriceFormatJson() ?>,
                        "prices": <?= /* @noEscape */ $block->getPricesJson() ?>
                    }
                }
            }
        }
    </script>
<?php endif; ?>