How to set a maximum word count on post titles

Code snippets to enable you get the most out of your WordPress blog

How to set a maximum word count on post titles


Code Snippets  1 Comment  138 views  
This WordPress code snippet demonstrates how to set a maximum word count on post titles.

There may be times when you want to limit the amount of characters that are displayed when displaying the title of your posts. Using this simple code snippet you can determine exactly the amount of characters that are displayed when displaying the characters. This may be used when listing all your latest posts on your home page for example.

 Set the maximum word count

You can adjust the amount of characters returned by changes the number in the snippet.
To apply this snippet, simply paste the following code in your WordPress theme functions.php file located in your current theme:

  1. function maxWord($title){
  2.     global $post;
  3.     $title = $post->post_title;
  4.     if(str_word_count($title) >= 10 ) //set this to the maximum number of words
  5.         wp_die( __(‘Error: your post title is over the maximum word count.’) );
  6. }
  7. add_action(‘publish_post’, ‘maxWord’);
function maxWord($title){
    global $post;
    $title = $post->post_title;
    if(str_word_count($title) >= 10 ) //set this to the maximum number of words
        wp_die( __('Error: your post title is over the maximum word count.') );
}
add_action('publish_post', 'maxWord');

Be sure to check out our other great WordPress Code Snippets and WordPress Articles.

1 Comment to "How to set a maximum word count on post titles"

  1. AfroDiva

    January 15, 2012

    comment

    Thanks for the code, it will really help to set the title and make sure your title is too long. Kudos!!!

    Reply

Leave a Comment