Using WordPress ‘comment_id_not_found’ PHP action

The comment_id_not_found WordPress PHP action is triggered when a comment is attempted on a post that does not exist.

Usage

add_action('comment_id_not_found', 'your_custom_function');
function your_custom_function($comment_post_id) {
    // your custom code here
}

Parameters

  • $comment_post_id (int): The Post ID.

More information

See WordPress Developer Resources: comment_id_not_found

Examples

Redirect to custom 404 page

Redirect users to a custom 404 page when they try to comment on a non-existing post.

add_action('comment_id_not_found', 'redirect_to_custom_404');
function redirect_to_custom_404($comment_post_id) {
    wp_redirect('/custom-404-page');
    exit;
}

Log comment attempts on non-existing posts

Log comment attempts on non-existing posts to a custom log file.

add_action('comment_id_not_found', 'log_non_existing_post_comment');
function log_non_existing_post_comment($comment_post_id) {
    error_log("Comment attempt on non-existing post ID: {$comment_post_id}\n", 3, "/path/to/your-log-file.log");
}

Send notification email

Send a notification email to the admin when someone tries to comment on a non-existing post.

add_action('comment_id_not_found', 'send_notification_email');
function send_notification_email($comment_post_id) {
    $admin_email = get_option('admin_email');
    $subject = "Comment attempt on non-existing post";
    $message = "A user tried to comment on a non-existing post with ID: {$comment_post_id}";
    wp_mail($admin_email, $subject, $message);
}

Display a custom message

Display a custom message to users who try to comment on a non-existing post.

add_action('comment_id_not_found', 'display_custom_message');
function display_custom_message($comment_post_id) {
    echo '<p><strong>Oops!</strong> The post you are trying to comment on does not exist.</p>';
}

Prevent comment form from displaying

Prevent the comment form from displaying when a user tries to comment on a non-existing post.

add_action('comment_id_not_found', 'prevent_comment_form_display');
function prevent_comment_form_display($comment_post_id) {
    add_filter('comments_open', '__return_false');
}