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.

Usage

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

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

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

Parameters

  • $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().

Examples

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");
fclose($debug_file);

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);
fclose($debug_file);

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);
}
fclose($debug_file);

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");
    fclose($debug_file);
    // 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"));
    fclose($debug_file);
}