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$contentwhich we are going to assign to thepost_contentlater on. - Declaring the global variable
$postthat contains all the post information from which we are going to fetch thepost_contentlater. - Creating a variable
$min_contentand 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_contentretrieved from the$postglobal variable to the variable$content. - The
str_word_countcounts the number of words in the$contentandifstatement checks if the value is less than the value we set in the$min_countvariable earlier. And if it is, the code inside theifblock 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
ifstatement - Closing our function.
- Hooking our function to the
publish_postaction, so that it always runs before publishing the articles and prevents the action if the minimum word count threshold isn’t reached.