Set a Minimum Word Count for Posts

This WordPress code snippet sets a minimum word count for posts on your website, preventing users from publishing posts that don’t meet this minimum requirement. This is useful for blogs, news sites, or any type of website that values longer, more substantial content.

The function wpcode_snippet_publish_min_words is added to the ‘publish_post’ action hook, which is triggered when a post is published. The function accepts two parameters, the ID of the post and the post object itself.

Inside the function, it checks if the word count of the post’s content is less than the specified minimum (100 words by default). The str_word_count function is used to count the number of words in the post content. If the word count is less than the minimum, the function halts execution of the script and displays an error message to the user using the wp_die function.

You can customize the minimum word count by modifying the $word_count variable to your preferred number. The error message can also be customized, but be sure to keep the %d placeholder where you want the minimum word count to appear in the message.

Note: The error message uses the esc_html__ function for security and internationalization purposes. It helps to prevent HTML injection attacks and makes the string translatable. If your website isn’t multi-language, the esc_html__ function can be replaced with a simple string.

PHP
/**
 * Prevent publishing posts under a minimum number of words.
 *
 * @param int     $post_id The id of the post.
 * @param WP_Post $post The post object.
 *
 * @return void
 */
function wpcoder_snippet_publish_min_words( $post_id, $post ) {
	// Edit the line below to set the desired minimum number of words.
	$word_count = 100;
	if ( str_word_count( $post->post_content ) < $word_count ) {
		wp_die(
			sprintf(
				// Translators: placeholder adds the minimum number of words.
				esc_html__( 'The post content is below the minimum word count. Your post needs to have at least %d words to be published.' ),
				absint( $word_count )
			)
		);
	}
}
add_action( 'publish_post', 'wpcoder_snippet_publish_min_words', 9, 2 );