You may want to set a minimum word count for posts on your WordPress website. So that no one will be able to publish a tiny article with very few words in it. In that case, you can use the code given below to set a minimum word count for all the articles. The code will check for the word requirement prior to publishing and returns an error if it doesn’t meet the number.
Usage
- To prevent all authors from publishing small articles that don’t meet your publishing standards.
Code
// Set minimum word count for post content
function minimum_post_word_count($content) {
global $post;
$min_count = 300; // 300 is the minimum word count
$content = $post->post_content;
if (str_word_count($content) < $min_count) {
wp_die( __('Error: at least write 300 words.') ); // error to show
}
}
add_action('publish_post', 'minimum_post_word_count');
Explanation
- Just a simple comment to identify the code
- Creating a function named “
minimum_post_word_count
” and passing the argument$content
which we are going to assign to thepost_content
later on. - Declaring the global variable
$post
that contains all the post information from which we are going to fetch thepost_content
later. - Creating a variable
$min_content
and assigning it the minimum word count that we want to force to all the articles prior to publishing. You can change the value “300” to any number of words as you wish. - Assigning the
post_content
retrieved from the$post
global variable to the variable$content
. - The
str_word_count
counts the number of words in the$content
andif
statement checks if the value is less than the value we set in the$min_count
variable earlier. And if it is, the code inside theif
block will run. Else, nothing happens. - Return an error message saying “Error: at least write 300 words.” using the
wp_die()
function. You can change the error code to anything you want. Be sure to just change the content inside the single quotes. - Closing the
if
statement - Closing our function.
- Hooking our function to the
publish_post
action, so that it always runs before publishing the articles and prevents the action if the minimum word count threshold isn’t reached.