In my functions.php
file I would like to remove the below filter, but I’m not sure how to do it since it’s in a class. What should remove_filter()
look like?
add_filter('comments_array',array( $this, 'FbComments' ));
It’s on line 88 here.
In my functions.php
file I would like to remove the below filter, but I’m not sure how to do it since it’s in a class. What should remove_filter()
look like?
add_filter('comments_array',array( $this, 'FbComments' ));
It’s on line 88 here.
You must be logged in to post a comment.
Thatâs a very good question. It goes down to the dark heart of the plugin API and best programming practices.
For the following answer I created a simple plugin to illustrate the problem with easy to read code.
Now we see this:
WordPress needs a name for the filter. We didnât provide one, so WordPress calls
_wp_filter_build_unique_id()
and creates one. This name is not predictable because it usesspl_object_hash()
.If we run a
var_export()
on$GLOBALS['wp_filter'][ 'wp_footer' ]
we get something like this now:To find and remove our evil action we have to go through the associated filters for the hook (an action is just a very simple filter), check if it is an array and if the object is an instance of the class. Then we take the priority and remove the filter, without ever seeing the real identifier.
Okay, letâs put that into a function:
When do we call this function? There is no way to know for sure when the original object is created. Maybe sometimes before
'plugins_loaded'
? Maybe later?We use just the same hook the object is associated to and jump in very early with priority
0
. Thatâs the only way to be really sure. Here is how we would remove the methodprint_message_3()
:Result:
And that should remove the action from your question (not tested):
Conclusion
'plugins_loaded'
. Not just when your plugin is called by WordPress.As long as you know the object (and you use PHP 5.2 or higher – current stable PHP version is 5.5, 5.4 is still supported, 5.3 is end of life), you can just remove it with the
remove_filter()
method. All you need to remember is the object, the method-name and the priority (if used):However you do a little mistake in your code. Don’t prefix
$this
with the ampersand&
, that was needed in PHP 4 (!) and it’s long-time overdue. This can render dealing with your hooks problematic, so just leave it out of the way:And that’s it.
I’m not sure but you can try using a singleton.
You must store the object reference in a static property of your class and then return that static variable from a static method. Something like this: