I need a function to limit the same user to leave max 1 comment every minute on my wordpress website (all posts).
1 Answer
Place the following into a custom plugin or into your child theme's functions file:
add_action("wp_insert_comment", function() {
global $current_user;
if ( !$current_user->ID ) return;
update_user_meta( $current_user->ID, "se_last_commented", time() );
});
add_action("init", function() {
if ( "wp-comments-post.php" == $GLOBALS['pagenow'] ) {
global $current_user;
if ( !$current_user->ID ) return;
$last_commented = (int) get_user_meta( $current_user->ID, "se_last_commented", 1 );
if ( !$last_commented ) return; // no time recorded
if ( (time() - $last_commented) > DAY_IN_SECONDS ) {
$date = date( "H -1-, i -2-, s -3-", DAY_IN_SECONDS - (time() - $last_commented) );
$date = str_replace( array('-1-','-2-','-3-'), array('hr','min','sec'), $date );
wp_die(sprintf( '<strong>ERROR:</strong> You have <u>%s</u> left until you can be able to post a comment.', $date ));
}
}
}, 0);
Basically what it does is it records the time integer of last time a user has posted a comment, and a user here means a logged-in WP user, and when any user submits a comment, WP will automatically check for last time this user has posted a comment and if it was longer than a day (DAY_IN_SECONDS
) then the process will be allowed, otherwise the user will see a death screen where they're notified how long they'll have to wait until they can be able to post a comment.
Hope that helps.