Wordpress: Shorten the title of posts or everything else you want
In a recent project I needed a section with short notes (common as asides) and a list of posts in the sidebar. The problem was only, that the length of the posttitle was to long for my theme and my layout suffered under this small bug. I also didnt wanted to change the wordpress core files which might be replaced by updates in future. So I wrote a solution for this and am sharing it to the public. Alle additions are only to make in your theme. Use it for everything you want, just let the note intact or link back to this site.
Now, lets get ready:
Create or open the functions.php in your wordpress templates folder. We will add a function which makes all the work for us everytime we will need it.
FIND
<?php
ADD BENEATH
// Wordpress Hack by Knowtebook.com
// Shorten any text you want
function ShortenText($text)
{
// Change to the number of characters you want to display
$chars_limit = 100;
$chars_text = strlen($text);
$text = $text." ";
$text = substr($text,0,$chars_limit);
$text = substr($text,0,strrpos($text,' '));
// If the text has more characters that your limit,
//add ... so the user knows the text is actually longer
if ($chars_text > $chars_limit)
{
$text = $text."...";
}
return $text;
}
Now we add a little code to the place within the loop for example to cut the title. It will call the function and short the title. Take attention to the title function: get_the_title() instead of the_title(), because the_title() would give out the title directly.
FIND
<?php the_title(); ?>
REPLACE WITH
<?php echo ShortenText(get_the_title()); ?>
You can use this for any text to shorten. You just have to double the function and give it a new name, so you can have different character limits.
Have fun and share!

Wordpress: Shorten the title of posts or everything else you want | mediaplana
Mar 25, 2008
ID: 1
[…] (more…) […]