Using WordPress ‘comment_footer_die()’ PHP function

The comment_footer_die() WordPress PHP function displays an error message at the bottom of the comments.

Usage

Let’s say you want to show an error message when a user tries to post a comment that doesn’t meet your guidelines. You can use the comment_footer_die() function to display a custom error message.

comment_footer_die("Your comment does not meet our guidelines.");

Parameters

  • $msg (string): The error message you want to display. This is assumed to contain HTML and be sanitized.

More information

See WordPress Developer Resources: comment_footer_die()
This function is included in WordPress since version 2.0.0. There is no indication of it being deprecated.

Examples

Basic Usage

This is a simple way to show an error message when a condition isn’t met in the comments section.

if ($comment_length > 200) {
    comment_footer_die("Your comment is too long. Please keep comments under 200 characters.");
}

This code will display an error message if a user tries to submit a comment over 200 characters long.

Checking for Spam

You can also use this function to check for potential spam in the comments.

if (strpos($comment_text, 'spam') !== false) {
    comment_footer_die("Your comment contains forbidden words.");
}

If the word ‘spam’ is found in the comment text, an error message will be displayed.

Profanity Filter

This function can be used to enforce a profanity filter in the comments section.

$profanities = array("profanity1", "profanity2");
foreach ($profanities as $profanity) {
    if (strpos($comment_text, $profanity) !== false) {
        comment_footer_die("Please refrain from using profanity in the comments.");
    }
}

If any word from the profanity list is found in the comment, it will display an error message.

If you want to prevent users from posting links in the comments, you can use this function.

if (strpos($comment_text, 'http') !== false) {
    comment_footer_die("Links are not allowed in comments.");
}

This will display an error message if ‘http’ is found in the comment text, indicating a link.

Checking for Empty Comments

To prevent users from submitting empty comments, you can use this function.

if (empty($comment_text)) {
    comment_footer_die("Your comment cannot be empty.");
}

If the comment field is empty, it will display an error message.