0

I created a WordPress plugin and I've used inline callable function for some hooks and filters, like this:

add_action( "init", function(){
   // some codes
} );

now I want to publish my plugin into WordPress repository but I'm not sure it is ok because actions and filters cannot be removed when we use anonymous functions. Now I want to know if WordPress accept my plugin or not and is it better to use named functions instead?

1

1 Answer 1

0

When developing a WordPress Plugin that uses custom do_action and apply_filters it's always better to use a callback function.

They don't explicitly say that you aren't allowed to use anonymous functions but whenever you can, and when it's appropriate, use a callback.
From the plugin development docs about actions

Create a callback function
First, create a callback function. This function will be run when the action it is hooked to is run.

The callback function is just like a normal function: it should be prefixed, and it should be in functions.php or somewhere callable. The parameters it should accept will be defined by the action you are hooking to; most hooks are well-defined, so review the hooks docs to see what parameters the action you have selected will pass to your function.

That being said, if you have some internal logic that relies on do_action/apply_filters that you don't want the user to mess with, then use an anonymous function.

It's your plugin, and it's up to you how much control and extensibility you want to provide your developer users.

Same goes for when you're using add_action/add_filter.
If you're using it on your own actions and filters and you don't want users to mess with them, use anonymous function.
But if you use it with built in actions/filters you might consider using a callback so users can decide if they want it or maybe modify it.

3
  • "you have some internal logic that relies on do_action/apply_filters that you don't want the user to mess with" is a big red flag that should make everyone run away from such a plugin Commented Feb 20, 2023 at 7:40
  • I would consider this the same as private methods/properties of a class, internal processes that you don't want client to have access to. If you think otherwise, please let me know Commented Feb 20, 2023 at 7:42
  • hooks are not internal, they inteface with the external wordpress core. having the implementation "hidden" in such a way means that whenever the implementation do not match your need you have to fork the plugin, which means much more effort to maintain your system once you started to use the plugin but discovered you need a slight modification to how it works. And all you save with an inline function is like 3 lines of code, does it realy worth it? Commented Feb 20, 2023 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.