Limit The Post Title in WordPress by Word Count

How to Limit The Post Title in WordPress by Word Count

in Functions
Google+ LinkedIn

This is not a function that you would need to use on daily basis, but I came across a reason to use it recently on a project and I thought it might be a good idea to share it here too. All it does is limit the post title by the number of words, just in case you don’t want the title to wrap onto a second line or third. I used this function to limit the post title in a featured sideshow since the size of the box is fixed and to fit caption text properly in that limited space, I had to limit the title captions to have maximum of 10 words.

WordPress has a not so well-known function wp_trim_words() to trim given text by word count. This is a very useful function for WordPress developers to make sure that their design/website do not break even if some user insert hundreds of words in a post title. To limit the post title you can use this code snippet in your theme. This following snippet will allow post title to have maximum of 10 words. Of course you can change word count limit based on your requirements.

    echo wp_trim_words( get_the_title(), 10, '' );

The above WordPress snippet is used on case basis in theme files but for whatever reason, if you are in need to limit all post titles by default then you can paste this following code snippet in your theme’s functions.php file and it will limit the post titles to 10 words all over the website. Although it’s not a good idea to limit the post titles by default, but the WordPress snippet is here if you want to use.

// limit the post title in wordpress by word count
function wcs_limit_word_count_in_post_title( $title ) {
    return wp_trim_words( $title, 10, '' );
add_filter( 'the_title', 'wcs_limit_word_count_in_post_title' );

Share the love

If you like this snippet, share it with others!

One Reply on "Limit The Post Title in WordPress by Word Count"

  1. Charles

    The code limit the post title sitewide.
    I only wanted it on the homepage.
    Please Help.

Leave a Reply

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