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:

1
2
3
4
5
6
7
8
9
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 (… 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:

1
2
3
4
5
6
7
8
9
10
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.