How to Show a Debug Message in WordPress

Share

Recently, I was trying to figure out how to show a typical debug, warning, or error message in WordPress (version 6.4.3), and all I could find was how to disable them. For reference: you use the function wp_trigger_error1, which is similar to PHP's trigger_error except it respects the WP_DEBUG constant setting. Here's an example of how you would use it:

<?php
$my_array = array();

/* Sets a key in my global array.
 * Emits a warning if the key already existed.
 */
function register_key_in_my_array($key, $value) {
    global $my_array;

    if(isset($my_array[$key])) {
        wp_trigger_error(
            __FUNCTION__,
            "Overwriting existing key \"".$key."\".",
            E_USER_WARNING
        );
    }

    $my_array[$key] = $value;
}

register_key_in_my_array('foo', 'bar');
register_key_in_my_array('foo', 'bar');

This will result in a message like:

Warning: register_key_in_my_array(): Overwriting existing key "foo". in functions.php on line 999

The first argument is the function name, e.g. __FUNCTION__. For class methods, you would use __METHOD__ instead. You may also use an empty string or a random string if you want.

The second argument is the message. The message won't be escaped, so don't use HTML in it that may come from user input. If you want to do that, first escape the HTML using the esc_html function.

The third argument is the error level, which are the following enumerated values:

  • E_USER_DEPRECATED - for functions and parameters that should no longer be used.
  • E_USER_WARNING - for logging mistakes that should be fixed.
  • E_USER_ERROR - for actual errors.
  • E_USER_NOTICE - for random message logging.

If the code that emits the message is computationally expensive, it may be a good idea to wrap put it inside an if(WP_DEBUG) condition.

<?php
if(WP_DEBUG) {
    /* query database to check the values are correct */
    if($some_mistake) {
        /* display warning */
    }
}

References

  1. Official documentation: https://developer.wordpress.org/reference/functions/wp_trigger_error/ (accessed 2024-06-07). ↩︎

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *