In a previous article I described how I’d written a little code in WordPress’ link-template.php file to automatically truncate long link titles so as to not break my design.
We revisit that code here to see if we can improve it a little.
Previously the truncation code was as follows:
$hack_length = strlen($title);
if ($hack_length > 34) {
$title = substr($title,0,30);
$title = $title . '…';
}
Which did the job quite effectively - discarding any characters after the thirtieth in a title and replacing them with a simple ellipsis. But the truncation was sometimes messy and awkward, in that the thirty-character cut could often be right in the middle of a word.
Now many webmasters would be happy enough with that, but I’m a picky little bastard – and my sights were set a little higher. That is, I wanted the cut to happen between words, not in the middle of one.
So I came up with some new code and it looks like this:
if (strlen($title) > 34) {
$whole_words = explode(" ", $title);
$return_title = "";
$test_return_title = "";
foreach ($whole_words as $word) {
$test_return_title = $return_title . " " . $word . " ...";
if (strlen($test_return_title) <= 34) {
$return_title = $return_title . " " . $word;
} else {
$return_title = $return_title . " …";
break;
}
}
$title = $return_title;
}
As before, this could should be inserted between lines 962 and 963 of the WordPress file, link-template.php. Note that if you made the previous modification, then you should replace that code with this.
The code works by building an array of whole words in a title then adding them, one-by-one, to a string while testing beforehand that the addition won’t exceed the previously set maximum length of the string.
I could further improve this by removing any trailing punctuation prior to appending the ellipsis, but I’m pretty happy with it as it stands.
Last Revision: May 6th, 2009 at 21:48