Thanks Michael, worked great for me too.
I did some minor changes though, I’ll share them if anyone is looking for the same function I was (getting titles under 40 characters);
First I added a $after variable so that truncated titles gets whatever you add after the truncation (in my case 3 dots ‘…’)
Then I noticed that adding these lines to my markup gave all the titles an extra whitespace before the title, so I converted it all into a function which I added to my functions.php and now I just need to call <?php short_title(); ?> in my template.
I know I could probably just have played around with the linebreaks and found the whitespace but this also has the advantage that it is easy to use where ever I want shorter.
Also added an $length variable so the final function looks like this:
function short_title($after = '', $length) {
$mytitle = get_the_title();
if ( strlen($mytitle) > $length ) {
$mytitle = substr($mytitle,0,$length);
echo $mytitle . $after;
} else {
echo $mytitle;
}
}
Call from the template:
<?php short_title(‘…’, 40); ?>