← All writing
 ·  1 min read

Log PHP Data In WordPress To Your Browser's Console

Debugging PHP can be a pain in WordPress. Add this handy code snippet to your theme's functions.php file. The function will log PHP data to your browser's console.

Log PHP Data In WordPress To Your Browser's Console

Debugging PHP can be a pain in WordPress. Add this handy code snippet to your theme's functions.php file. The function will log PHP data to your browser's console.

php
/**
 * @param ...$data
 *
 * @return void
 */
function my_console_log(...$data) {
    $json = json_encode($data);
    add_action('shutdown', function() use ($json) {
       echo "<script>console.log({$json})</script>";
    });
}

// Example usage
my_console_log(['foo' => 'bar'], null, 1, 'hi');