Wordpress - How to debug vars inside function at functions.php file?

You can simply use var_dump() to do this. That is how I check values inside functions and filters.

I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable

?><pre><?php var_dump( $variable_to_test ); ?></pre><?php

The pre tags dump a nice readable array/object/string depending on the value. Inside your function you can just do

?><pre><?php var_dump($ad_posts); ?></pre><?php 

after ksort( $ad_posts );.

Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen


To debug these values you don't have to display them in browser. Rather then do:

error_log(your-variable-or-whatever);

And check your error log in wp-content/debug.log.

To make it working you have to have define( 'WP_DEBUG_LOG', true ); set in your wp-config.php.

EDIT: As @nmr pointed out, define( 'WP_DEBUG', true ); is also required.


The proper and correct way to do this would be using XDebug and some kind of IDE that supports it, while working on development locally.

The easiest setup I can recommend would be using Local by Flywheel (free) for local development: https://localbyflywheel.com/

Local has option under Utilities (for a site) to add XDebug configuration to PHPStorm, after clicking that button reopen the project in PHPStorm and you will see a debug configuration already setup for that site.

PHPStorm EAP (eap was free previously) can be downloaded here (also has 30 day trial): https://blog.jetbrains.com/phpstorm/2019/04/phpstorm-2019-1-2-preview-191-7141-5/

Docs on setting up XDebug: https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html

You can then set a breakpoint in your code and inspect it using XDebug.

The options above do work in a crunch, but the correct way to debug PHP is using an IDE and XDebug, and will save you TONS of time if you learn to do it the right way.

Using error_log:

To expand on others responses about error_log output, if it's an array or something that's not a string, it's best to use print_r and set return to true:

error_log( 'MY STUFF: ' . print_r( $something, true ) );