One Weird Trick to Debug WordPress Quickly

Have you ever needed to build a new feature or fix some bugs for a WordPress site? Chances are the code you need to work with is way too complicated to understand quickly.


You can use a combination of var_dump()  and wp_die()  to do some basic introspection, but that’s really just a snapshot of a moment in the code.

What you need to understand to fix the bug is to know where the application execution started, what was triggered and how you ended up at a certain point. What you need is a trace.

Here’s a function I just wrote for getting a nice and comprehensible call trace. It is probably more resource-intensive than some other alternatives but it is short, understandable, and gives nice output (Exception->getTraceAsString()).

function generateCallTrace()
    $e = new Exception();
    $trace = explode("\n", $e->getTraceAsString());

    // reverse array to make steps line up chronologically
    $trace = array_reverse($trace);
    array_shift($trace); // remove {main}
    array_pop($trace); // remove call to this method
    $length = count($trace);
    $result = array();
    for ($i = 0; $i < $length; $i++)
        $result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
    return "\t" . implode("\n\t", $result);

Example output:
1) /var/www/test/test.php(15): SomeClass->__construct()
2) /var/www/test/SomeClass.class.php(36): SomeClass->callSomething()

This function is so useful!

You get a really nice list of what led to a function being executed, complete with file locations and the exact line of code there the next function is called.

Instead of wasting spending time in Sublime Text jumping between files doing the same thing manually, use generateCallTrace() and learn in minutes what might have taken you days to fully grasp.