A fast way to debug that I use to debug in WordPress, In fact I got used to it so much that I use it on any PHP environment or framework that i work on. The method is debugging php variables and arrays to the console (the browser console) and will print out at runtime as the code is being executed in the browser the variable value.
Just a small method that in WordPress I just add it (always) to the functions.php
file, and in other php frameworks, add it as a general global helper function.
# The Method
/**
* Send debug code to the Javascript console (PHP Console Debugging)
*/
function debug_to_console($data, $tag = 'JHONNY') {
if(is_array($data) || is_object($data)) {
echo("<script>console.log('" . $tag. ": " .json_encode($data)."');</script>");
} else {
echo("<script>console.log('" . $tag. ": " .$data."');</script>");
}
}
When added to functions.php
It allows me to call the function anywhere in my theme,
The first argument $data
– It’s the variable or array that I want to to see his state (the value).
The second argument $tag
– It’s an optional tag you can add, so as it is printed out in the console, you can identify it better.
# On Small Projects
On small projects mostly there is no need to add the second argument, so as it is above, it will alwyas just print "JHONNY: "
before the variable, so I know that this is printed out from this function.
So all you need to do is just give it the var you want to debug:
debug_to_console($tax_name)
It will look like this (In the browser console):
# On larger Projects
On larger projects, usually, I add the second argument with the class name or tepmplate page it belongs to with the var name, something like:
debug_to_console($image_url,"footer.php - imageUrl")
It will look like this (In the browser console):