To create a custom `write_log()` function for WordPress, you can use the `error_log()` function to write messages to the error log. This function will allow you to log information, warnings, errors, or any other messages during development or debugging.
Here’s a simple implementation of the `write_log()` function:
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); } } }
Explanation:
1. The function checks if `WP_DEBUG` is set to `true`. This ensures that the log messages will only be written when debugging is enabled in your WordPress configuration. It’s a standard practice to log messages only in the development environment.
2. If the `$message` passed to the function is an array or an object, it uses `print_r()` to convert it to a string representation before logging it. This way, you can log complex data structures for better debugging.
3. If the `$message` is a scalar value (string, integer, float, etc.), it directly logs it using `error_log()`.
Usage:
You can use the `write_log()` function anywhere in your WordPress code to log messages. For example:
function my_custom_function() { $data = array('foo' => 'bar', 'hello' => 'world'); write_log('My custom message.'); write_log($data); }
Remember to call `my_custom_function()` while `WP_DEBUG` is set to `true` in your `wp-config.php` file.
To view the log messages, you can access the error log file of your web server. The location of the error log file depends on the server configuration. For example, in Apache, it’s often found in the server’s error log directory. In PHP configurations, you can also set a custom log file by modifying the `error_log` directive in `php.ini`.