Pergunta

I want to limit the length of the product name on the front end. I have the following code in the list.phtml

<a class="product-item-link" href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>">
<?= /* @escapeNotVerified */ $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a>

How I can limit the product name to 50 characters for example?

Thank you

Foi útil?

Solução

You can use like below sample code.

<?php
$productName = $_helper->productAttribute($_product, $_product->getName(), 'name');
$len = strlen($productName);
?>
<a class="product-item-link" href="<?php echo /* @escapeNotVerified */ $_product->getProductUrl() ?>">
    <?php echo substr($productName,0,50); ?>
    <?php if($len > 50) echo '...'; ?>
</a>

substr function will truncate product name (string)

Outras dicas

Try below code

<a class="product-item-link" href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>">
    <?php /* @escapeNotVerified */ substr($_helper->productAttribute($_product, $_product->getName() , 'name'),0,50); ?>
</a>

You can use Pure CSS for this, rather on code level, limiting character from code may me a little bad for SEO.

Read the full answer here https://magento.stackexchange.com/a/319927/26733

Thanks

Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top