If, how, and where conditionals are applied depends on the filter being used. Very specific filters are less likely to need conditionals than very broad filters. How filters work is indeed rather difficult to grasp at first. I say it’s well worth spending the time to really understand how filter and action hooks work. They are fundamental to customizing WP. The multi-page section on hooks in the Plugin Handbook may help in gaining an understanding. The concept applies to themes as well.
I find it very useful to locate the source code where hooks are applied, by calling either apply_filters()
or do_action()
. This is the only good way to see what is being passed to your callback in context, as well as what happens to return values (in the case of filters, returned values from action hooks are ignored). Those functions serve as the “trigger” that “fires” the specific action or filter. They call all callback functions that were added to the specific tag in question. Additionally, the inline documentation in source is often informative.
For filters, apply_filters()
takes whatever is returned by the callback and returns that value itself. Source code reveals what happens to the returned value after applying all the added filters. Take the ‘pre_comment_approved’ filter as an example. Check out the source code. You can see two parameters will be passed to your callback. The first parameter ($approved, after the tag itself) should always be returned, altered or not, by callbacks. As you can see, the return is in turn returned by the wp_allow_comment()
function.
By checking the code reference, we learn wp_allow_comment()
is called by wp_new_comment()
. Checking its source code, we see the returned value is part of what gets saved when the new comment is inserted into the DB. WP handles the comment based on the value saved for $commentdata['comment_approved']
, which can be 1
(true), 0
(false), or 'spam'
.
Part of understanding hooks involves understanding the context in which they are used. Each filter’s context is different, and the only way to see the context is by examining the source code around where the filter “fires”. I hope this furthers your understanding of hooks. Once you truly understand how these work, I think you’ll find it’s really not that hard to understand after all. It just takes an effort to grasp the concept.