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
- A comment to distinguish the code snippet from other codes in your functions.php.
- Creating a function
wpt_limit_title_lengthand passing it the$titleargument which we are going to use to retrieve and assign thepost_titlefrom the$postglobal variable. - Assigning the
$postglobal variable that contains our post data. - Assigning the
post_titlefrom the$postto the variable$title. - Creating an
ifstatement that counts the number of words in the post title using the PHP functionstr_word_countand 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 theifstatement. If the word count is less than the specified number of words, allow the action. - Return an error using the
wp_diefunction. Change the error message between the single quotes to your choice. - Closing the
ifstatement. - Closing the function.
- Hooking our function to the
publish_postusing theadd_actionso that our code will run before the post gets published.