Skip to content
On this page

Hooks

Forme has a superbly clean way of organising WordPress hooks, via the app/config/hooks.yaml file. No more searching through hideously convoluted functions.php files.

The Hook Config Yaml

Have a look at app/config/hooks.yaml. You'll notice there are two top levels, actions and filters. They do exactly what they say on the tin - you put your action hook definitions in the first and your filter hook definitions in the other.

Hook Definitions

Each definition looks something like this:

yaml
actions:
# ...
    - hook: init # The hook name
      class: Foo\Bar\ClassName # The fully qualified class name where the method you want to call is
      method: __invoke() # optional - defaults to `__invoke()` i.e. a callable class
      priority: 10 # optional - defaults to 10 as per WordPress
      arguments: 1 # optional - defaults to 1

That should all be pretty self-explanatory - but let's take a look at a concrete example.

Let's say we need to hook onto the wp_check_filetype_and_ext filter. We're going to have a service class CsvMimeTypeCorrector with a method fix that's going to handle this. We can see in the definition over on wordpress.org that we need 5 arguments. We therefore need to add this to the yaml:

yaml
filters:
# ...
    - hook: wp_check_filetype_and_ext
      class: My\App\Services\CsvMimeTypeCorrector
      method: fix
      arguments: 5

Our filter is now all hooked up and ready to rumble.

The main advantage of doing it this way is that all of your hook definitions are clearly visible and labelled in one place - you won't need to hunt around as much. You should also find this much more readable than add_action and add_filter function calls.

Code generation

You can use the Forme codegen to help you wire up hooks to existing class methods.

bash
forme make action action_name

or

bash
forme make filter filter_name

The interactive cli will then ask you to select the class and method, and add the priority and argument count if you need to. It will then create a new entry in hooks.yaml.

You can of course then edit that entry manually and make any necessary adjustments as you see fit.

Made by Moussa Clarke @ Sanders Web Works with ❤️