How to Display Custom Error Messages in WordPress Admin

There are many ways to display custom error messages in WordPress. You must have often seen WordPress itself show various error messages in the admin area. Nags to update to the latest release, for example. Various plugins also inject their custom messages highlighting new features, or asking you to take action.

In this article, I’ll show you how to show a custom error message in the in the WordPress editor after updating the status of a post. This code can be easily modified an error message anywhere in the WordPress admin. Let’s say for example that you want to limit the character length of the title of the post. We all know that search engines only show the first 55-60 characters in a post’s title. So it makes sense to create a rule disallowing page titles longer than that.

Display Custom Error Messages in WordPress via the “add_settings_error” function

Open up functions.php, or your plugin for custom PHP code and paste in the following:

function show_editor_message($messages)
{
    global $post;
    $post_title = $post->post_title;
    if (str_word_count($post_title) > 55 ) {
        $error_message = 'Title should be shorter than 55 characters';
        add_settings_error('title_long_error', '', $error_message, 'error');
        settings_errors( 'title_long_error' );
        $post->post_status = 'draft';
        wp_update_post($post);
        return;
}
    return $messages;

}
add_action('post_updated_messages', 'show_editor_message');

If you don’t know how to add code like this, check out our earlier tutorial on inserting WordPress code snippets. In this code, we do the following:

  1. Hook into the action when the post is updated.
  2. Create a new error message with the handle “title_long_error” via the “add_settings_error” function.
  3. Display the error with “settings_errors()”
  4. Set the post status back to draft – since we don’t want to publish the post
  5. Update the post, and return.

This will create the following error message as shown in this screenshot:

Display custom error messages in WordPress

You can see that the custom error message displayed in the WordPress admin looks exactly like the kind of notifications that WordPress itself displays to you when something goes wrong. You can read up more about the types of messages, and the color coding of the add_settings_error function here. The type of message generates a CSS class that you can style to create your own WordPress admin messages with a unique look. By default, the message is “error”, meaning it shows up as above with a red bar on the left hand side.

This technique to display custom error messages in WordPress, can be used for showing them anywhere – not just on the post editor. All you need is to find the appropriate action to hook into!

Speak Your Mind

*