Chip's Tips for Developers

Contains coding, but not narcotic.

Wiping the mystery out of WordPress debugging

September 24th, 2007 4:33:52 pm pst by Sterling Camden

Speaking of the deficiencies of PHP, another one is the complete lack of built-in debugging capabilities.  Sure, you can find debuggers for PHP, if you’ve got the time and ability to configure them on your server.  I guess if I was really serious about PHP I’d have to get one of those, but so far I only use PHP for WordPress customization, so it hardly seems worth the effort.

Some people will tell you that you shouldn’t need a debugger.  That it’s a sign of lazy programming.  But PHP has so many pitfalls, and WordPress has so many actions and interactions between plugins and themes provided by so many different developers, that I think you’re excused if you need a little help figuring out just what the heck is going on in your code.

When writing a plugin or modifying a theme for WordPress, usually all I need to know is the order of events and the values in various variables.  Sometimes you can get away with inserting “echo” statements in your code — but sometimes you can’t, like when your code executes ahead of a “wp_head” action that wants to add headers.  Besides, randomly placed “echo” statements can easily get lost from view in the whirl of words and images that comprise your theme and content.

So, I developed a simple little plugin that collects debug statements and prints them out nicely above the footer of your theme, or below the admin footer, whichever gets executed first.  I call it WiPeD, for “WordPress Printf Debugger”.  Anywhere in your code, you can call WPD_print() and pass it whatever text you want to output.  The lines of text are aggregated in a session variable until they are output together (in separate divs, surrounded by a single containing div).  Thus you can use styling to set the messages off from the rest of your blog, if you desire.

Here’s an example, from a project I’m currently working on.  My plugin was producing no results, and I couldn’t figure out why.  So I added some calls to WPD_print():

Then, when I executed the code to trigger this action, here’s what I saw at the bottom of my page:

That tells me that I got into my function and passed the tests, but the post has no content at that point.  Now I just need to figure out why.

See the enclosed readme file for more details.  Have fun debugging your PHP!

UPDATE: get an updated version here.

Posted in PHP, Web, Wildly popular, WordPress | 19 Comments » RSS 2.0 | Sphere it!

Better Tag Cloud