avatar Deluxe Blog Tips About Projects

Debugging functions

While developing WordPress plugins and themes, I usually need to see values of variables. While PHP already offers print_r and var_dump functions, it's not convenient to use them to output variables in a beautiful way. So I made some debugging helper functions to do that.

Simple debugging helper functions

These helpers are mostly used by me and my team at eLightUp and the source code is available on Github. Here they are:

<?php
function d( ...$args ) {
	echo '<pre>';
	foreach ( $args as $arg ) {
		print_r( $arg );
	}
	echo '</pre>';
}

function dd( ...$args ) {
	d( ...$args );
	die;
}

function v( ...$args ) {
	echo '<pre>';
	foreach ( $args as $arg ) {
		var_dump( $arg );
	}
	echo '</pre>';
}

function vd( ...$args ) {
	v( ...$args );
	die;
}

function l( ...$args ) {
	foreach ( $args as $arg ) {
		error_log( print_r( $arg, true ) );
	}
}

function vl( ...$args ) {
	ob_start();
	foreach ( $args as $arg ) {
		var_dump( $arg );
	}
	error_log( ob_get_clean() );
}

The function names are inspired by Laravel, where:

NameDescription
ddump
dddump and die
vvar_dump
vdvar_dump and die
llog, which logs the output of variables into the error log file. In WordPress, it's the wp-content/debug.log
vlvar_dump and log, which logs the output with "var_dump"

To make it available everywhere, I usually put these functions in file in the "must-use plugins" folder, e.g. wp-content/mu-plugins/helpers.php. So I don't have to activate a plugin to use these functions.

Advanced debugging with Frog

I also created a simple library called Frog to output variables separately from the normal workflow in PHP/WordPress. It works this way:

  • Start Frog, which you can access to it from an URL like https://frog.test
  • In your WordPress themes or plugins, to debug variables, call f( $var1, $var2 ), and the output of the variables will be displayed in the Frog's URL
Frog debug screen
Frog debug screen

This way, the normal workflow is not corrupted, and nothing like debugging info will be outputted on your website. And it's very helpful when debugging Ajax requests.

For details, please see the Frog repo.

Other debugging options

  • Debug Toolkit is a nice plugin that offers similar debugging functions with beautiful output from VarDumper and Kint libraries.
  • Ray is a cool debugging app that works independently with your PHP apps. Ray actually is the inspiration for Frog.

Comments