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_length
and passing it the$title
argument which we are going to use to retrieve and assign thepost_title
from the$post
global variable. - Assigning the
$post
global variable that contains our post data. - Assigning the
post_title
from the$post
to the variable$title
. - Creating an
if
statement that counts the number of words in the post title using the PHP functionstr_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 theif
statement. If the word count is less than the specified number of words, allow the action. - Return an error using the
wp_die
function. Change the error message between the single quotes to your choice. - Closing the
if
statement. - Closing the function.
- Hooking our function to the
publish_post
using theadd_action
so that our code will run before the post gets published.