Magento 2 -Limit the length of the product name on the front end.
-
14-04-2021 - |
Frage
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
Lösung
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)
Andere Tipps
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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange