• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

WP Thinker

The WordPress Playground

  • Snippets
  • Best
  • Guides
  • Reviews
Home / Code Snippets

March 3, 2021 Jayan

Limit the Title Length in WordPress

Sometimes, you may want to limit the length of the title one would be able to enter in the title section of WordPress posts or pages. Especially if you have strict editorial guidelines that you want to enforce on all the authors even when they accidentally violate them. No worries, it is just a few lines of code that will limit the title length on all of your future posts. If they exceed the limit you set, they won’t be able to save the article. As simple as that.

Usage

  • To prevent the authors on your website from publishing articles that have titles too long.
  • To maintain the visual aspects of your website by avoiding titles that are too long overflowing the available area.
  • To provide your readers short and precise titles without long titles.

Code

// Limit WordPress title length
function wpt_limit_title_length($title){
   global $post;
   $title = $post->post_title;
   if (str_word_count($title) >= 20 ) {
   wp_die( __('Error: choose a title with less than 20 words.') );
   }
}
add_action('publish_post', 'wpt_limit_title_length');

Explanation

  1. A comment to distinguish the code snippet from other codes in your functions.php.
  2. Creating a function wpt_limit_title_length and passing it the $title argument which we are going to use to retrieve and assign the post_title from the $post global variable.
  3. Assigning the $post global variable that contains our post data.
  4. Assigning the post_title from the $post to the variable $title.
  5. Creating an if statement that counts the number of words in the post title using the PHP function str_word_count and if it is greater than or equal to the specified number on the right (in this case 20 words, change it to any number you want) execute the command inside the if statement. If the word count is less than the specified number of words, allow the action.
  6. Return an error using the wp_die function. Change the error message between the single quotes to your choice.
  7. Closing the if statement.
  8. Closing the function.
  9. Hooking our function to the publish_post using the add_action so that our code will run before the post gets published.

Primary Sidebar

Related Articles

Footer

WP Thinker is a website that publishes everything related to WordPress, Plugins, Themes, SEO, Blogging, etc.

  • Facebook
  • Twitter
  • Pinterest

Copyright © 2023 · WP Thinker

  • About Us
  • Advertise
  • Write for Us
  • Privacy Policy
  • Terms and Conditions
  • Contact Us
This website uses cookies to serve you better. By continuing to use this website, you agree to our cookie and Privacy Policy.