The remove_filter()
is necessary to avoid the callback from being called recursively, which would result in a memory issue due to a never-ending function execution.
And that recursion could happen because the callback is hooked to get_post_metadata
which is invoked via the get_metadata()
function which the callback calls.
So you need to first “unhook”/unregister the callback from the hook and only then you may call get_metadata()
.
Otherwise, you’d end up with something like:
WP applies the filter (calls apply_filters( 'get_post_metadata', ... ))
- your callback is called
- the callback calls get_metadata()
- WP applies the filter
- your callback is called
- the callback calls get_metadata()
- WP applies the filter
- your callback is called
- the callback calls get_metadata()
- WP applies the filter.....
Or:
your_callback() {
your_callback() {
your_callback() {
your_callback() {
..... it never ends ...
So your code is good in that it’s avoiding the unwanted recursion.
However, I noticed that you’re not properly removing the filter:
// You added the filter like so:
add_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), -1, 4);
// Then in the callback, you're removing it like this:
remove_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), 0);
// And later in that callback, the filter is added back:
add_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), 0, 4);
And the problem is, when removing a filter/action, the priority and number of accepted parameters must match the same values you used when adding the filter:
// If you added the filter like so:
add_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), -1, 4);
// Then use the same parameters when removing the filter:
remove_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), -1, 4);
// And not like this — priority should be -1 and this is missing the fourth parameter:
remove_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), 0);
And if you initially added the filter like so, then you should also add it back inside the callback the same way — using the same parameters:
// Like this:
add_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), -1, 4);
// Not this: (priority doesn't match)
add_filter('get_post_metadata', array(WPKWP::CLASS_NAME, 'get_post_metadata'), 0, 4);