Best Of Joanne

Actions and Filters and Classes, Oh My! « Weblog Tools Collection

Ever wondered how you can manipulate WordPress filters and actions that are defined inside a PHP class?

I did! I was working on a project recently that needed a plugin. The only problem was that the plugin was inserting some unnecessary cruft into the header of my theme. So, I figured I’d just use the remove_filter function WordPress provides… right?

Hold on a second! It’s not working!? But I put in the function name just how the codex explains it:

remove_filter(‘wp_head’, ‘the_crufty_function’);

Why would it not work? Time to do some troubleshooting… So, I opened up the main plugin PHP file in my code editor and began to look around. What’s this? It’s a class! Hmm… But why should that make a difference?

It seems that WordPress requires a special reference to the function if it is defined inside a class. If you, the reader, are at all familiar with PHP classes then you probably know that you can usually access a class’s functions like this:

$the_class_initiator_variable->some_function();

So, lets give that a try:

remove_filter(‘wp_head’, $the_crufty_class->the_crufty_function);

Still nothing… Oh boy… What do I do now? I guess we’ll try some Googling…

…Hmm…

…Not finding much…

Well… after much searching and trying different things I finally came upon this:

remove_filter(‘wp_head’, array(&$the_crufty_class, ‘the_crufty_function’));

It works! Wonderful!

You take the class initiator variable and the name of the function and put it in an array. Simple as that!

Note: No, that ampersand is not a typo! It sets up a reference to the original variable instead of copying it’s value. You’d be surprised how many people don’t know what the ampersand does in PHP. I didn’t know for the longest time.

Also, because the remove_filter and remove_action functions are so similar this method applies to both.

There you have it! Just a quick little tip regarding an issue that doesn’t seem to be very well documented. I’m sure some of the experts out there already know of this but, I didn’t. I’m willing to assume there are some people out there like me who are racking their brains over this very issue.

Hope it helps!

via Actions and Filters and Classes, Oh My! « Weblog Tools Collection.

1 Response to "Actions and Filters and Classes, Oh My! « Weblog Tools Collection"

Leave a Comment

CommentLuv Enabled

Why ask?