Need a reliable way to track bugs in WordPress? This tutorial walks you through setting up a custom write_log()
function using PHP’s error_log()
to simplify debugging.
Define the write_log()
Function
Here’s how to use error_log()
conditionally with WP_DEBUG:
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); } } }
Why This Matters
- Debug Mode: Ensures logging only happens during development.
- Structured Logs: Makes object/array logs readable.
- Efficient Debugging: Track both expected and unexpected output.
Logging in Action
function my_debug_function() { write_log('Debug started'); $test_array = ['key' => 'value']; write_log($test_array); }
Turn on Logging
define('WP_DEBUG', true); define('WP_DEBUG_LOG', true);
Find the log in wp-content/debug.log
or your server’s error log folder. Customize location via php.ini
settings if needed.
Debugging Tips
- Disable logs on live sites:
WP_DEBUG = false
- Keep log files secure and hidden from public access.
- Limit usage to development environments only.
Further Documentation
By using a tailored logging function, developers gain full control over debugging messages and performance monitoring in WordPress.