I have searched for a suitable explanation of the difference between add_filter()
and apply_filters()
in here but couldn’t find one.
Can anyone tell me what information or logic to consider before using add_filter
or apply_filters
in one context.
That makes the use of one imperative and not the other ?
-
Is it correct that
add_filter
just adds a function to the queue of functions waiting to be executed on a variable andapply_filters
executes the functions in order? -
Is it also correct that
apply_filters
when called with an argument (the name of the function to be run) will execute that function before all the others (if they exist) in the queue?
Most of the following can be found in the Codex:
apply_filters
In essence:
You use
apply_filters
to filter a given$value
– with respect to the value itself as well as optionally provided variables$var_1
through$var_n
.add_filter
In essence:
You use
add_filter
to hook a custom function to the given filter action ($tag
), which you might have generated byapply_filters
before (or it was a built-in filter action or stems from a plugin/your theme).So, here’s a fictional example:
Now, if we just call our function as is, the initials are printed from left to right—because this is what we defined as default behavior.
The second time, we get the initials in reverse order—because the filter function
__return_true
, which is hooked to our filter action, always returnsTRUE
and thus makes the initials be output from right to left.The example above is the classic example that kills a newby developer..
explained in a rude – people-friendly way, you can use apply_filters to create a specific custom filter you can later on modify through add_filter.
On the other side, if you use an already made hook, you can straight use add_filter..
The logic, is the tipical non-logic of development, so you need to look more examples and practice a bit in order to “understand” how they work..
I know that even my explanation could not sound totally clear, (and most of our coworkers could kill me for being incorrect) but it looks to me the most understandable explanation I have found on the Internet..