In apply_filters()
apply_filters( $tag, $value, $var ... );
I’m having trouble wrapping my head around the $value
and $var
. I read the codex and it sounds like the $value
can be modified, $var
not, but I haven’t found any examples of this in the wild. It seems to be used as a way to pass a variable. In which case, what’s the difference between that and the $var
?
Try to see the function with better names:
So when that function is called as:
You can use â¦
⦠and get two variables passed to that function. You return the first, the second provides just more context:
The additional variables are there to make your decisions easier, not to change those too.
What are Filters?
Hooking into a Filter
In order to let users change some specific data (a value, the output of a function etc.) filter hooks are provided via
apply_filters
functions.These filter hooks include the name (or tag) of the filter and at least the function name that is to be used to filter (i.e., alter in some way) the data.
To alter the title of a post, you can use the
the_title
filter hook, which is defined as follows:This means, the filter has the tag/name
the_title
, the first parameter$title
is the data that is to be changed (i.e, the post title) and the second parameter$id
is extra information (in this case the post ID).To display the title of every post in UPPERCASE, for example, you can use the following line:
If we take a look at the
add_filter
function, we see it is defined as follows:We only specified the first and second (required) parameter, while the third and fourth paramter is set to its respective default value (i.e.,
10
and1
).A More Complex Filter
If you want to filter only a certain post, you can use the extra information (in case of this filter: the ID). In order to do so, you have to specify the number of parameters (which is 2 in this case), and in order to do this again, you have to specify the priority parameter (which comes before the number of arguments).
Suppose we want to affect only the title of the post with the ID 42, then it looks like this:
In this case, we have to specify all four available parameters.
What Parameters Do I Have?
To identify the (number of) available parameters of a certain filter, you have to look up where it is defined (in this case: here).
References:
apply_filters
functionadd_filter
function