Debugging is essential for WordPress development. This guide shows you how to create a custom write_log() function in WordPress using error_log(). With this, you can log info, warnings, errors, and more to keep track of issues during development.
Custom write_log() Function in WordPress
Use this function to write messages to the error log while developing:
function write_log($message) {
if (true === WP_DEBUG) {
if (is_array($message) || is_object($message)) {
error_log(print_r($message, true));
} else {
error_log($message);
}
}
}
Function Explained
- WP_DEBUG Enabled: Logging only works when WP_DEBUG is true in
wp-config.php. - Object/Array Support: Converts arrays and objects to readable strings before logging.
- Scalar Logging: Directly logs strings, numbers, and other simple data types.
Example Usage
function my_custom_function() {
$data = array('foo' => 'bar');
write_log('Custom debug message');
write_log($data);
}
Enable Debugging in wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
Logs are saved in your server’s error log file. You can customize this in your php.ini.
Tips for Secure Debugging
- Disable debugging in production:
WP_DEBUG = false. - Don’t log sensitive data like passwords or user details.
- Clean up logs regularly to avoid bloat.
Helpful Links
This simple technique helps you keep your development workflow smooth and efficient.
