SMOR.tv  > Tutorials  > WordPress Tutorials  > WordPress Title Trimming Tutorial

WordPress Title Trimming Tutorial

02.06.2010 Bookmark and Share

This tutorial will show you how to trim title lengths for long post or page titles, which can be helpful for keeping the layout of your website consistent. My example uses the WordPress get_the_title template tag, but this could easily be modified for other uses.

Start off by opening your functions.php within your WordPress theme folder:
(wp-content\themes\themename\functions.php)
If you don’t have a one, you can create a new file and call it functions.php.

Next copy the following code into your functions.php, save and then upload the file. Watch out for the PHP tags when copying the code, you’ll most likely only need them if you’re starting a blank document.

<?php
// Title Trimmer (Version 3)
// Sam Morris - 12.28.2009
// www.smor.tv

function title_trimmer($title , $maxLength)
{

	$titleLength = strlen($title); // get the amount of characters in the title

	// start conditional
		if ($titleLength > $maxLength) // if the title length is over the max length, then we start the trimming process.
			{
				$trimmedTitle = substr_replace($title,"",$maxLength);
				echo $trimmedTitle;
				//echo $trimmedTitle . "..."; //use this instead of the line above if you prefer having a ... after your trimmed titles.
			}
		else
			{
				echo $title;
			}
}
?>

WordPress has many built in functions, but the functions.php is where you can place your own custom functions. When your theme’s templates are loaded, so will the functions.php allowing you to use your own functions throughout your theme. Open the template that needs the title trimming, or if you just want to try it out you can open single.php (for posts) or page.php (for pages).

find the_title, which is what most themes will use by default. When you find it, you can replace it will the following code. The title trimming function has 2 arguments, the first is what should be trimmed and the second argument is the maximum length of characters. In my example I’m trimming the WordPress title down to a maximum of 10 characters.

<?php title_trimmer(get_the_title() , 10); ?>

Save, upload, and then create a test page or post to see the title trimming in action.

Sam Morris WordPress Tutorials

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.