• Hello all!

    So I have a question for all the developers out there. I have been searching around for a plugin that will enable me to set a minimum word count for the comments section of each post (essentially a reversed Twitter), but I cannot seem to find one, and as the comments section is part of WordPress and not a plugin I was hoping someone here could help me.

    As you will see the website is still in progress so everything on there is for testing, but the critical element and its USP is this idea that there needs to be a minimum word count for comments and replies – as that discourages hate replies and short offensive comments and promotes informed discussion of debate.

    I don’t know if this would require a few lines of code or a whole custom plugin but I am hoping it’s not the latter. It would be a great help if someone could aid me with this predicament and I look forward to hearing a solution!

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • I don’t know why this was harder than it should have been. I expected some kind of hook specifically for comment errors but I couldn’t find anything. So what the below code is doing is killing the page if a comment content doesn’t have a minimum length of 100 words. Do note that str_word_count() is not a perfect function so there are chance it could fail but for a simple validation I think it will work in this case. Finally, there’s a back button courtesy of bonger from WordPress Stack Exchange.

    /**
     * Additional comment validation
     *
     * @param Integer $post_id - The ID of the given Post user is commenting on.
     *
     * @return void
     */
    function mcgee_comment_validation( $post_id ) {
    	
    	if( ! ( isset( $_POST, $_POST['comment'] ) && ! empty( $_POST['comment'] ) ) ) {
    		return;
    	}
    	
    	$minimum_count	= 100;
    	$content 		= $_POST['comment'];
    	$back_link		= sprintf( __( '<br /><a href="javascript:history.go(-1)">Back To %1$s</a>' ), get_the_title( $post_id ) );
    	
    	if( str_word_count( $content ) < $minimum_count ) {
    		wp_die( __( 'Comments have a minimum length of 100 words.' ) . $back_link );
    	}
    	
    }
    add_action( 'pre_comment_on_post', 'mcgee_comment_validation' );

    The above you could add as an MU Plugin, Normal Plugin, or add straight to your themes functions.php file ( assuming it’s a child theme or non-updatable theme ).

    Thread Starter iggyb3

    (@iggyb3)

    Hey,

    Sorry I haven’t replied sooner, I just found the email notification of a reply in my spam folder!

    I have just added it into the themes functions.php file at the bottom and it seems to be working perfectly! Thanks a lot for taking the time to figure this one out, it’s a great help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Minimum word count for comments’ is closed to new replies.