3

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

Robert
  • 2,166
  • 2
  • 37
  • 82

4 Answers4

6

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)

Kishan Patadia
  • 5,609
  • 3
  • 24
  • 36
2

Try below code

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

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

Shuvankar Paul
  • 410
  • 6
  • 17
0

I tried the code by Kishan Patadia, it works on catalog page but not on home page, shall we need to run upgrade command?