I have a php file which is part of a wordpress plugin. I need to debug an issue we are having. I want to find out what a variable’s value is. How can I print the variable’s value to console? echo or chrome or firefox extensions have been suggested. I couldn’t get echo to output to console (echo â$variablename";
) and neither using the firephp extension for firefox.
4 comments
Comments are closed.
To answer your question, you can do this:
but I would recommend doing one of the things @Ishas suggested instead. Make sure
$error
doesn’t contain anything that can mess up your script.If you are thinking about the javascript console, you can not do this from PHP.
You have a few options you could choose from:
For a quick check for a variables value I would use var_dump, it will also show you the data type of the variable. This will be output to the browser when you request the page.
Logging to the DevTools console from PHP in WordPress
Here you can see my solution for the problem in action while debugging coupon logic in WooCommerce. This solution is meant for debug purposes, only. (Note: Screenshot not up to date, it will also expose private members.)
Features
Solution
wp-debug.php
wp-config.php (partially)
Usage
<head>
is rendered:<head>
is rendered (in templates, etc. / use when the above does not work):Output format
Special thanks to
You can write a utility function like this:
The you may call the function like this:
and this will output to console like this:
Notice the quotes replaced with “-“. It is done so that message does not mess up your script as pointed by @Josef-Engelfrost
You may also go one step further and do something like this:
and call the function like this:
It will output error in console.