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 (… 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.


Comments

2 responses to “WordPress: Shorten title”

  1. ] Project Data [#]

    ] Project Data [#]…

    WordPress: Shorten title – elektroelch.net…

  2. Great piece of code. Very hard to find though. I have added “How To Automatically Shorten/Truncate WordPress Post Titles Using The Functions.php File” to the comments to make it easier to find.

Leave a Reply

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

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)