How to limit WordPress title length

When you want to keep your post titles as short as possible and you work with multiple authors, this might be a problem. Whether you’re starting a fashion blog, food blog or any other type of a blog, everyone would have to take care of their titles, count words or letters and it would probably be a hard time doing that every time when you write a new article.

So how do you limit a post title in WordPress so it automatically takes care of the title length being showed on your page?

Let’s start with a simple solution.

  1. Open functions.php in your theme
  2. Paste the following code:
  3. function max_title_length( $title ) {
    $max = 20;
    if( strlen( $title ) > $max ) {
    return substr( $title, 0, $max ). " …";
    } else {
    return $title;
    }
    }
  4. Place the next function wherever you want in your theme. For example, if you want to show shortened titles on your homepage, you want to place this code into your Main Index Template (index.php)

add_filter( 'the_title', 'max_title_length');

As you can see in the code, variable $max is used to limit the length of your post title. You are free to change it to any number you want – be aware that the optimal length of your title is between 55 and 60 characters.

There you go. If you have called the function in your Main Index Template, your titles will be displayed shortened and after, in our case 20 characters, three dots will be revealed to show there is more to display.

By doing the same, you are free to hook the function wherever you want it – be it header, footer, sidebar…

If you liked this article, check out our resources that will help you become a better webmaster.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

One thought on “How to limit WordPress title length

Leave a Reply

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