Using WordPress ‘pre_comment_on_post’ PHP action

The pre_comment_on_post WordPress PHP action fires before a comment is posted on a specific post.


add_action('pre_comment_on_post', 'your_custom_function');
function your_custom_function($comment_post_id) {
    // Your custom code here


  • $comment_post_id (int): The ID of the post on which the comment is being submitted.

More information

See WordPress Developer Resources: pre_comment_on_post


Prevent comments on a specific post

This code prevents users from submitting comments on a post with the specified ID.

add_action('pre_comment_on_post', 'prevent_comments_on_specific_post');
function prevent_comments_on_specific_post($comment_post_id) {
    $post_to_disable_comments = 123; // Change this to the post ID on which you want to disable comments
    if ($comment_post_id == $post_to_disable_comments) {
        wp_die('Sorry, comments are not allowed on this post.');

Limit comment length

This code limits the length of comments to 200 characters.

add_action('pre_comment_on_post', 'limit_comment_length');
function limit_comment_length($comment_post_id) {
    $comment_content = $_POST['comment'];
    if (strlen($comment_content) > 200) {
        wp_die('Your comment is too long. Please keep it under 200 characters.');

Block comments containing specific words

This code prevents comments containing specific words from being submitted.

add_action('pre_comment_on_post', 'block_comments_with_specific_words');
function block_comments_with_specific_words($comment_post_id) {
    $blocked_words = array('spam', 'example'); // Add words to this array that you want to block
    $comment_content = strtolower($_POST['comment']);

    foreach ($blocked_words as $word) {
        if (strpos($comment_content, $word) !== false) {
            wp_die('Your comment contains a blocked word.');

Require a minimum comment length

This code requires comments to be at least 30 characters long.

add_action('pre_comment_on_post', 'require_minimum_comment_length');
function require_minimum_comment_length($comment_post_id) {
    $comment_content = $_POST['comment'];
    if (strlen($comment_content) < 30) {
        wp_die('Your comment is too short. Please write at least 30 characters.');

Close comments after a specific date

This code closes comments on all posts after a specific date.

add_action('pre_comment_on_post', 'close_comments_after_specific_date');
function close_comments_after_specific_date($comment_post_id) {
    $close_date = '2023-05-01'; // Change this to the date you want to close comments
    $current_date = date('Y-m-d');
    if ($current_date >= $close_date) {
        wp_die('Comments are closed on this post.');