Changing Comment Error Messages

WordPress offers many ways to customize itself, yet the error messages that are displayed when a site visitor unsuccessfully posts a comment leave a lot to be desired. At least when comments are closed the error message starts with a word that is capitalized, as seems proper.

While not the focus of this blog post, I’d like to point out that there are no back buttons on any of pages that display error messages for comment submissions. Why not? I’m going to show you how to add one.

To me, little things like the way that errors are displayed make a big difference. I like site visitors to feel they’ve got an overall website experience that is perfect. By default, when comments are submitted, they are sent to wp-comments-post.php, and they go through some simple validation. If validation fails, then WordPress uses it’s own wp_die function to display one of a few different error messages, which as of WordPress 3.5.1 are still hard coded. You might be tempted to change the error messages by hacking wp-comments-post.php, but next time you upgrade your WordPress installation, you’re going to lose those changes.

My Solution:

With a quick search I found that I could customize the look of the WordPress error page. In a blog post named Custom WordPress “Comment Error” Page, Velvet Blues Web Design & Development shows how to quickly create an alternative template for wp_die generated errors. My solution for changing the text of those error messages, and for adding a back button, starts there.

/**
 * Customize wp_die so it doesn't look so cheesy
 */
function my_custom_die_handler($message, $title='', $args=array())
{
  // Get the path to the custom die template
  $template = get_theme_root().'/'.get_template().'/custom_die.php';

  // If not an admin page, and if the custom die template exists
  if( ! is_admin() && file_exists( $template ) )
  {
    // The default response code is 500
    $defaults = array( 'response' => 500 );

    // Combine the args and defaults
    $r = wp_parse_args( $args, $defaults );

    // Determine what type of error we are dealing with
    if( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) 
    {
      // If no title, try to make one
      if ( empty( $title ) ) 
      {
        $error_data = $message->get_error_data();

        if ( is_array( $error_data ) && isset( $error_data['title'] ) )
          $title = $error_data['title'];
      }

      // Get the actual errors
      $errors = $message->get_error_messages();

      // Depending on how many errors there are, do something
      switch ( count( $errors ) )
      {
        case 0 :
          $message = '';
          break;
        case 1 :
          $message = '<li>' . $errors[0] . '</li>';
          break;
        default :
          $message = '
            <li>' . join( "</li><li>", $errors ) . '</li>
          ';
          break;
      }

    }
    else if( is_string( $message ) )
    {
      $message = '<li>' . $message . '</li>';
    }

    /**
     * Since wp-comments-post.php does not allow error 
     * messages to be changed, the error message string 
     * is run through str_replace to customize.
     */
    $lame_messages = array(
      'Sorry, comments are closed for this item.',
      'please fill the required fields (name, email).',
      'please enter a valid email address.',
      'please type a comment.'
    );

    $replacements = array(
      'Sorry, comments are closed.',
      'All comment form fields are required. Please try again.',
      'Please enter a valid email address.',
      'No comment in your submission. Please try again.'
    );

    // Save the original error message for later comparison
    $pre_replacements = $message;

    // Do the comment form error message replacements
    $message = str_replace( $lame_messages, $replacements, $message );

    if(
      // If the back link was set in the args
      ( isset( $r['back_link'] ) && $r['back_link'] ) OR

      // Or if message identified as comment error
      $message !== $pre_replacements
    )
    {
      // Show the back button
      $back_link = '
        <p>
          <a href="javascript:history.back()" class="back">Back</a>
        </p>
      ';
    }

    // If the title is empty, set it as "Error"
    if( empty( $title ) )
      $title = 'Error';

    require_once( $template );

    die();

  }
  else
  {
    _default_wp_die_handler( $message, $title, $args );
  }
}

// Intermediate function is necessary to customize wp_die
function swap_die_handlers()
{
  return 'my_custom_die_handler';
}

add_filter('wp_die_handler', 'swap_die_handlers');

// End of example code ---

As you can see, I’m just using PHP’s str_replace function to swap out the WordPress error messages for my own. If a comment error message is swapped out, I let my template know to display the back button. By the way, all of this code is in my functions.php file.

The custom_die.php file is a stand-alone template. It doesn’t use any WordPress functions, and I believe the reason it should be that way is that WordPress may decide to use wp_die before many of the functions are available. The variables I pass to my custom_die.php file are simple, in fact, there are only 3.

<head>
  <!-- The title goes in the head -->
  <title><?php echo $title; ?></title>
</head>
<body>
  <!-- The message and back link go somewhere in the body -->
  <ul>
    <?php echo $message; ?>
  </ul>
  <?php
    // Do we need a back button?
    if( isset( $back_link ) )
    {
      echo '<p>' . $back_link . '</p>';
    }
  ?>
</body>

You will probably want to add a bunch of styling like I did. Once you are done, you will have satisfaction in knowing that even the error pages of your blog look like the rest of your website, AND they will say what you want them to say.

5 thoughts on “Changing Comment Error Messages”

Comments are closed.