Debugging WordPress

Enable Debugging

WordPress provides a debug facility that is set up by editing the wp-config.php file in your WordPress directory as follows:

// Turns WordPress debugging on
define('WP_DEBUG', true);

// Tells WordPress to log everything to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);

// Doesn't force the PHP 'display_errors' variable to be on
define('WP_DEBUG_DISPLAY', false);

// Hides errors from being displayed on-screen
@ini_set('display_errors', 0);

A detailed explanation of debug settings is provided in the WordPress documentation. However, the settings shown above will result in all php errors, notices, and warning being written to the debug.log file in the wp-content directory.

Live Monitor the Debug Log

To monitor the content of the debug.log live in Linux, open a terminal and use the command:

tail -f debug.log

This will display additions to the log file as they occur. To terminate the monitoring press Ctrl+C.

Add your own debug messages to the log

Debugging in this way gets more useful when coupled with the facility to add your own debug messages to the log file. This can be done by adding the following function to the functions.php file in your theme.

function log_msg($message) {
    if ( WP_DEBUG === true ) {
        if ( is_array($message) || is_object($message) ) {
            error_log( print_r($message, true) );
         } else {
            error_log( $message );
         }
     }
}

Now you can use the log_msg($msg) function anywhere within your development code.

Leave a Reply

Your email address will not be published.