I'm planning on working on some rules that check the use of add_action() and add_filter() when the action or filter is from WordPress core. The wp-hooks library facilitates this, and the wp-hooks-generator library facilitates this for hooks in third party plugins and themes (although I'm only concentrating on the WordPress core hooks for now).
I'll open a PR once I have something working.
When I call add_action( 'foo', $callback ) or add_filter( 'foo', $callback ):
- The signature of the callback function should be checked against the parameters that get passed to the hook
- The number used in the
$accepted_args parameter should match the number of parameters that the callback accepts
- A filter should not be used as an action, nor vice versa
- The callback for
add_filter must return a value with a type which is compatible with the type passed to it
- The callback for
add_action must return void
Notes:
- It's fine for the callback function to accept fewer parameters than are passed to the hook (but see point above about
$accepted_args)
- There is no requirement to have a docblock on the callback because it's the job of PHPStan to figure out parameter types and raise errors due to implicit
mixed, etc
- We could also look up the literal hook name, eg
plugin_action_links_{$plugin_file} and see if we get a match for dynamic hook names (stretch goal)
I'm planning on working on some rules that check the use of
add_action()andadd_filter()when the action or filter is from WordPress core. The wp-hooks library facilitates this, and the wp-hooks-generator library facilitates this for hooks in third party plugins and themes (although I'm only concentrating on the WordPress core hooks for now).I'll open a PR once I have something working.
When I call
add_action( 'foo', $callback )oradd_filter( 'foo', $callback ):$accepted_argsparameter should match the number of parameters that the callback acceptsadd_filtermust return a value with a type which is compatible with the type passed to itadd_actionmust return voidNotes:
$accepted_args)mixed, etcplugin_action_links_{$plugin_file}and see if we get a match for dynamic hook names (stretch goal)