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

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)

  • thank you how I can put some characters at the end of the name for example .... – Robert Oct 24 '17 at 16:27
  • you can count string. for example if greater than 100 then print '...' after product name. – Kishan Patadia Oct 24 '17 at 16:27
  • can you add this in your answer please? – Robert Oct 24 '17 at 16:29
  • added. please check – Kishan Patadia Oct 24 '17 at 16:31
  • How this can be done in admin grid? – jafar pinjar Sep 12 '18 at 11:42
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>
  • you test this code is not work? – Robert Oct 24 '17 at 16:27
  • @Abhishek I have truncated product name but special characters are getting corrupted while truncating product names. Is there any solution to prevent this? – Chintan Kaneriya Apr 3 '19 at 5:50
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.