Over a million developers have joined DZone.

Set Minimal Comment Limit In WordPress

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

The reason for comments being turned on a blog is to add more in-depth discussion to a certain post. But some people comment just to get a link back to their own site, these comments will consist of things like "nice post", "thanks", that add nothing to the discussion of the post.

Most of the time blog owners will use moderation to delete these types of comments from appearing on the site, but if you have a popular site this can take up a lot of time. If you are getting annoyed with having to delete all comments like this then we can place a minimal character count on your comments.

For this you can use the filter preprocess_comment to check the comment before it is saved to the database. Within this filter you can check the character count of the comment by using the strlen() function.

If the character limit is less than the value you set it as then we can display an error message to user by using the wp_die() function.

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
	$minimalCommentLength = 20;
	if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
        {
		wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
        }
	return $commentdata;
}

View Gist



The Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".

Topics:

Published at DZone with permission of Paul Underwood , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}