WordPress: Shorten title

A frequently asked question in WordPress forum is how to shorten the title of a post to a predefined number of characters and to append a “…”.

The problem is solved with a few lines of code:

add_filter( 'the_title', 'short_title' );
function short_title( $title ) {
$chars = 20;
if ( strlen( $title ) > $chars ) {
$title = substr( $title, 0, $chars );
$title .= " …";
}
return $title;
}

The variable $chars has to be set to the number of characters you want to have in your title and in line 6 you have to define the text to replace the omitted part of the title (&hellip; is the typographically correct version of three points, called ellipse).

It’s a bit disadvantageous that the title could be cut in the middle of a word. If you like you can extend the function accordingly:

add_filter( 'the_title', 'short_title' );
function short_title( $title ) {
$chars = 20;
if ( strlen( $title ) > $chars ) {
$title = substr( $title, 0, $chars );
$title = substr($title, 0, strrpos( $title, ' ' ) );
$title .= " …";
}
return $title;
}

If you copy the function into the file functions.php of your theme all calls of the_title will return the shortened title.