Helpful functions for debugging data anywhere in a ClassicPress project

When working on a plugin (or theme!) how many times do you print_r() or var_dump() to see what data is stored in some variable, array, or object?

Here’s the functions I use when creating plugins. I just drop the file into my C:/ drive and then do a include_once('C:/debug.php'); in my wp-config.php file (on localhost). This gives gives me access to the functions everywhere. :slight_smile:

:warning: These functions should not be placed on a production website! :warning:

debug()

The debug() function takes 1-4 arguments. It exposes the data in variables, arrays, objects. It tells you the data type and the value. See the comments with the function. As a basic example, doing this:

debug($my_array, 'xyz');

…might produce something like this…

$xyz [array]

Array
(
    [type] => all
    [color] => multi
    [size] => small
)

line()

The line() function takes the same arguments, except that it only works with basic variables. This function is best suited for use in loops where you want to expose the data in a series of k/v pairs. See the comments with the function. As a basic example, doing this:

$my_array = [
    'type' => 'all',
    'color' => 'multi',
    'size' => 'small'
];
foreach ($my_array as $k=>$v) {
    line($v);
}
foreach ($my_array as $k=>$v) {
    line($v, $k);
}

…might produce something like this…

> all [string]
> multi [string]
> small [string]
> $type = all [string]
> $color = multi [string]
> $size = small [string]

:boom: And that’s it. Once included, you can use these functions anywhere you might find yourself in a day of ClassicPressing. PS. If I’ve shared my debug() and line() functions with you previously, these are updated versions!

debug.php

6 Likes

Hi,
are you aware of the kint-debugger?

There is a wordpress plugin (seems not maintained any more), so i updated it for my own needs (latest kint version). Works well with ClassicPress (not sure about WP, but who cares ;))

If would like to take a look you will find it here: https://github.com/erichk4/cp-kint-debugger

Simple usage:

<?php d( $var ); ?>

and let the magic happen… :slight_smile:

Greets Erich

2 Likes

Hi @erichk4,

No, I wasn’t aware of kint-debugger for WP. For full debugging I fall back on the Debug Bar + extensions…but it’s rare that I need an actual suite. In terms of debugging, I can mostly get by by just dumping variables. Mostly, I wanted something simple – ie, no builds, dependencies, updates, or maintenance required. Drop it in, then forget about it ever after. :slight_smile:

If I had a policy on “Platform Compatibility” with my plugins, this would be it. :smiley:

I just use error_log( print_r( $var, true ) ); and tail the logs :slight_smile:

3 Likes

That’s another interesting method. Admittedly, I’m not a fan of viewing error logs…so much so that I wrote a plugin, PHP Error Log Viewer, to colorize and filter it for easier consumption. :slight_smile: