Jul
16
2010

Shorten Your Post Titles in WordPress


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;
}
If you liked this, please share it.

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

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

Discussion 1 Comment

  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

Leave a Reply

Your email address will not be published. Required fields are marked *

*


To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.