Make WordPress Post Title Shorter

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 characters in your title, just in case you don’t want it to wrap onto a second line.
I used in a woocommerce product showcase page. The client had really strict requirements in how that page could display. To avoid misplacements from the titles we decided to make it to limit the number of character to fit in two lines.

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


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;
}

Then call the short_title function in your loop:



Related posts