Limiting Node Title Lengths In Drupal
Friday, December 12th, 2008Im just wrapping up development on WinForAYear.com and because of how I’ve formatted the nodes, I needed a way to shorten the titles if they exceeded a set length. This feature would come in handy in many situations, like presenting a table of stats where the title could easily overlap into another column.
Now you could easily edit the title css to include a set width with “overflow:hidden” hiding the excess, but then you would be left with abruptly ending titles with no indication that there is more. However, if there were “…” attatched to the end of the shortened titles, things would be more clear.
The Solution
Open up your node.tpl.php file in your drupal theme. Look for this line:
<?php print $title; ?>
and replace it with:
<?php
// if title is longer than 28 characters, cut off the rest and add “…”
if(strlen($title) > 28){ print substr($title, 0, 28).”…”;}
else { print $title; }
?>
The Breakdown
if(strlen($title) > 28)
If the title is greater than 28 characters (including spaces).
{print substr($title, 0, 28).”…”;}
Display the first 28 characters of the node title and attatch “…” to the end.
else { print $title; }
Now we don’t want “…” being displayed if the title isn’t too long, so here we just display the title unchanged.
