Trim Post Titles

I've spent many hours customizing the theme that adorns my other site, so much so that it barely resembles the original. The work was not confined to css alterations either as I rewrote a large chunk of code that takes care of things behind the scenes. If you're interested, a complete changeset is listed in the style sheet. (riteturnonly.com) [that site now uses a different theme]

One of the things I did was redesign the front page (home.php) splitting the content into two columns thereby giving it a magazine-ish look. Yes I know, the author already created magazine-type variations of this theme but I wanted to see if I could do it myself by studying the existing variations. It wasn't that difficult. The bio info at the bottom is static.

A problem I ran into immediately was an alignment issue caused by long post titles. Because the content blocks are a certain width, long post titles wrapped to the second line causing that particular block to drop out of alignment with respect to the others. It really wasn't a big deal but being the picky person I am it sort of irked me. Okay, it downright pissed me off. Using a little magic in the functions.php file I came up with the right excerpt length for the content but I needed a way to do the same for the post titles. Unfortunately information on the subject is non-existent in the Codex and the few pieces of code I whipped up just didn't produce the results I wanted. Fortunately we have Google.

For anyone who finds him/herself in the same boat wanting to trim post titles here is how. Add the following to your theme's functions.php file...

function trim_title() {
$title = get_the_title();
$limit = "x";
$pad="...";

if(strlen($title) <= $limit) {
echo $title;
} else {
$title = substr($title, 0, $limit) . $pad;
echo $title;
}
}

What this does is create a new function called trim_title(). Adjust the line that reads $limit = "x"; to your desired length. In my case I used 20. So it would read $limit = "20";. (Don't include the period) If the title is less than 20 characters it will do nothing. If it is more it will trim it to the specified length.

Next, open the file that contains the post title you want to trim. In my case it was home.php. Look for the_title() in the line that constructs your permalink and replace it with your new function trim_title(). That's it.

About the author
Len has been blogging for over 10 years and is a rabid WordPress fan. In addition to blogging here you can find him writing the occasional article and toiling away in the forums at WeblogToolsCollection.com. He also hangs out at the WordPress support forums lending a hand where he can. You can also find him at his other blog LenKutchma.com

6 Responses to “Trim Post Titles”

  1. Kartik Rao says:

    Brilliant! Thanks a lot!

  2. Marc D says:

    Just what I needed for my next theme. :)
    Marc D´s last blog ..Ben XO ft DJ Liquid – Pyrrenial Power PunchMy ComLuv Profile

Leave a Reply

CommentLuv Enabled