Debugging in WordPress is an important part of developing and maintaining a WordPress site. It helps to identify and fix errors, improve performance, and enhance the overall user experience. Debugging can be enabled by using the WP_DEBUG setting. This setting is located in the wp-config.php file, which is located in the root directory of your WordPress installation.
The first thing you should do when developing a WordPress plugin or theme is to enable debugging mode in WordPress.
Debugging PHP code is part of any project, and WordPress is not exceptional.
If your code or other codes have something wrong, WordPress raises warnings and error messages. If you can’t see any message, maybe your code doesn’t have any error or warning.
WordPress provides a debug tool to display what may be the cause of an error on your website.
By default, in WordPress, debugging is turned off, to enable it you have to change a root file of the WordPress.
To enable debugging in WordPress, you need to edit the wp-config.php file. This file is located in the root directory of your WordPress installation. You can edit this file using a text editor such as Notepad++.
Open the “wp-config.php” file in your WordPress root folder and find the below code near the bottom of the file.
define('WP_DEBUG', false);
The WP_DEBUG setting is a Boolean (true/false) value that enables debugging mode in WordPress. When set to true, it will display all errors, warnings, and notices on your website. This is useful for troubleshooting and debugging problems with your site.
Edit the file and replace the below code with the above.
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );
If there is any wrong with the code, you can find the messages in the log file. To see the log file go to the “/wp-content/debug.log” file.
How to Log Your Own Debugging in WordPress
We are going to do the job in the simplest way to display the message on the page. Create a function like below and call the function everywhere you want to display the message.
function hs_log($message) {
if (WP_DEBUG === true) {
if (is_array($message) || is_object($message)) {
error_log(print_r($message, true));
} else {
error_log($message);
}
}
}