请求修改WordPress评论洪水过滤代码,实现单帖300秒评论间隔
针对单篇文章的WordPress评论间隔限制修改方案
原代码会对全站所有文章强制300秒的评论间隔,要实现仅限制用户在当前评论的单篇文章内的评论频率,可以通过以下修改后的代码实现:
function wpdocs_dam_the_flood_per_post( $dam_it, $time_last, $time_new ) { // 获取当前评论对应的文章ID $current_post_id = isset( $_POST['comment_post_ID'] ) ? (int)$_POST['comment_post_ID'] : 0; if ( !$current_post_id ) { return $dam_it; // 没获取到文章ID就沿用原有规则 } // 获取当前评论用户的标识:登录用户用ID,访客用邮箱 $user_id = get_current_user_id(); $comment_args = array( 'post_id' => $current_post_id, 'number' => 1, 'orderby' => 'comment_date_gmt', 'order' => 'DESC', 'status' => 'approve' ); if ( $user_id ) { $comment_args['user_id'] = $user_id; } else { $comment_args['author_email'] = isset( $_POST['email'] ) ? $_POST['email'] : ''; if ( empty( $comment_args['author_email'] ) ) { return $dam_it; // 访客没留邮箱,不限制 } } // 查询该用户在当前文章的最新评论 $last_comment = get_comments( $comment_args ); if ( $last_comment ) { $last_comment_time = strtotime( $last_comment[0]->comment_date_gmt ); // 判断当前评论和同文章最后一条评论的间隔是否小于300秒 if ( ( $time_new - $last_comment_time ) < 300 ) { return true; // 触发洪水限制 } } // 不符合限制条件,允许评论 return false; } add_filter( 'comment_flood_filter', 'wpdocs_dam_the_flood_per_post', 10, 3 );
代码说明:
- 优先获取当前评论对应的文章ID,确保只针对当前文章做判断
- 区分登录用户和访客:登录用户用用户ID匹配,访客用提交的邮箱匹配,保证判断的准确性
- 仅查询当前文章内该用户的最新评论,计算时间间隔,只有间隔小于300秒时才触发评论限制
- 若获取不到文章ID或访客未提供邮箱,会沿用原有全局规则,避免出现异常
内容的提问来源于stack exchange,提问作者Jawequo
相关产品推荐
相关产品推荐

