Using WordPress ‘debug_fwrite()’ PHP function

The debug_fwrite() WordPress PHP function is used to write contents to the file that is being used for debugging purposes.


Here’s a basic usage of debug_fwrite() function:

$debug_file = fopen("debug.txt", "w");
debug_fwrite($debug_file, "Debugging message");

In this example, the function writes the string “Debugging message” into the file “debug.txt”.


  • $fp (mixed): This parameter is required but not used.
  • $message (string): This is the message to log. It is required.

More information

See WordPress Developer Resources: debug_fwrite()

This function is primarily used for debugging purposes. It’s similar to the function error_log(). Remember to close the file using fclose() after using debug_fwrite().


Basic Usage

Writing a simple message to the debugging file.

$debug_file = fopen("debug.txt", "w");
debug_fwrite($debug_file, "This is a test message");

Logging Variable Values

Logging the value of a variable to the debugging file.

$myVar = "Test value";
$debug_file = fopen("debug.txt", "w");
debug_fwrite($debug_file, "Value of myVar: " . $myVar);

Logging Array Values

Logging the values of an array to the debugging file.

$myArray = array("val1", "val2", "val3");
$debug_file = fopen("debug.txt", "w");
foreach($myArray as $value) {
    debug_fwrite($debug_file, "Array value: " . $value);

Tracking Function Calls

Logging when a specific function is called.

function myFunction() {
    $debug_file = fopen("debug.txt", "w");
    debug_fwrite($debug_file, "myFunction() was called");
    // rest of the function...

Error Logging

Logging an error message when an operation fails.

$operationSuccess = false; // Let's say an operation failed
if (!$operationSuccess) {
    $debug_file = fopen("debug.txt", "w");
    debug_fwrite($debug_file, "Operation failed at " . date("Y-m-d H:i:s"));