Jul
16
2010

Shorten Your Post Titles in WordPress

by   |  Posted in Tutorials  |  2 comments

This is not a function that you would need to use often, but I came across a reason to use it recently and I thought it might be a good idea to share it. All it does is limit the number of words in your title, just in case you don’t want it to wrap onto a second line. I used it in the featured slideshow on Magazine Premium since the size of the boxes is fixed.

Include this in your functions.php file between the PHP tags:

function short_title($after = '', $length) {
	$mytitle = explode(' ', get_the_title(), $length);
	if (count($mytitle)>=$length) {
		array_pop($mytitle);
		$mytitle = implode(" ",$mytitle). $after;
	} else {
		$mytitle = implode(" ",$mytitle);
	}
	return $mytitle;
}

Then you can use it within the WordPress loop like this:

<?php echo short_title('...', 8); ?>

If you would rather count by characters instead of just words, you can add this function to your functions.php file instead of the one above:

function short_title($after = null, $length) {
	$mytitle = get_the_title();
	$size = strlen($mytitle);
	if($size>$length) {
		$mytitle = substr($mytitle, 0, $length);
		$mytitle = explode(' ',$mytitle);
		array_pop($mytitle);
		$mytitle = implode(" ",$mytitle).$after;
	}
	return $mytitle;
}

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/9dXczo

Discussion 2 Comments

  1. Loy on August 3, 2010 at 1:54 pm

    Wow, you read my mind :) this is exactly what I needed!

    Thanks so much :)

    Loy

  2. Marion on February 3, 2011 at 7:14 am

    Thank you again…I’ve googled so many times for this solution to no avail. I’ve actually accomplished what I wanted in less than 5 minutes.