One of the most interesting and powerful design components of the WordPress software are hooks. They are not unique to WordPress, but it is the main software I use that relies on them so heavily. There are two types of hooks – filters, and actions. The main difference is that a filter expects some sort of data as input, and will return some sort of data. For example, there is the classic capital_P_dangit
filter, which makes sure that WordPress is always properly capitalized. The input is some text, and the output is some text, which has the P in WordPress capitalized, should you happen to forget to do so. Action hooks could be anything – for example, you could write one to send an email whenever the capital_P_dangit filter actually changes the output.
A tricky thing about filters is that any piece of code can add and remove filters at will. This can make debugging a bit difficult sometimes. You might be looking at a piece of code which contains a line like
return apply_filters( 'foo', true );
And then you are surprise to see a lower case p come out. What gives? Well, maybe some piece of code has removed that filter (or maybe no filters were ever added to it to begin with). In these cases, it can be handy to know what filters are actually defined. I have duckduckgoed this several times recently, but keep forgetting the exact syntax, so I am writing it here for my future self. I can simply log all filters with:
error_log(json_encode($GLOBALS['wp_filter']));
Another very handy debugging tool in wordpress is wp_debug_backtrace_summary
which prints out a brief stacktrace of all the functions that have been called to get to the current line of code
P.S. Too bad typewriters don’t have the capital_P_dangit
function built in :)