|
| 1 | +# 6. Hooks |
| 2 | + |
| 3 | +The Abilities API provides [WordPress Action Hooks](https://developer.wordpress.org/apis/hooks/) that allow developers to monitor and respond to ability execution events. |
| 4 | + |
| 5 | +## Available Actions |
| 6 | + |
| 7 | +### `before_execute_ability` |
| 8 | + |
| 9 | +Fires immediately before an ability gets executed, after permission checks have passed but before the execution callback is called. |
| 10 | + |
| 11 | +```php |
| 12 | +/** |
| 13 | + * Fires before an ability gets executed. |
| 14 | + * |
| 15 | + * @since n.e.x.t |
| 16 | + * |
| 17 | + * @param string $ability_name The name of the ability. |
| 18 | + * @param mixed $input The input data for the ability. |
| 19 | + */ |
| 20 | +do_action( 'before_execute_ability', $ability_name, $input ); |
| 21 | +``` |
| 22 | + |
| 23 | +**Parameters:** |
| 24 | + |
| 25 | +- `$ability_name` (`string`): The namespaced name of the ability being executed (e.g., `my-plugin/get-posts`). |
| 26 | +- `$input` (`mixed`): The input data passed to the ability. |
| 27 | + |
| 28 | +### `after_execute_ability` |
| 29 | + |
| 30 | +Fires immediately after an ability has finished executing successfully, after output validation has passed. |
| 31 | + |
| 32 | +```php |
| 33 | +/** |
| 34 | + * Fires immediately after an ability finished executing. |
| 35 | + * |
| 36 | + * @since n.e.x.t |
| 37 | + * |
| 38 | + * @param string $ability_name The name of the ability. |
| 39 | + * @param mixed $input The input data for the ability. |
| 40 | + * @param mixed $result The result of the ability execution. |
| 41 | + */ |
| 42 | +do_action( 'after_execute_ability', $ability_name, $input, $result ); |
| 43 | +``` |
| 44 | + |
| 45 | +**Parameters:** |
| 46 | + |
| 47 | +- `$ability_name` (`string`): The namespaced name of the ability that was executed. |
| 48 | +- `$input` (`mixed`): The input data that was passed to the ability. |
| 49 | +- `$result` (`mixed`): The validated result returned by the ability's execution callback. |
| 50 | + |
| 51 | +## Usage Examples |
| 52 | + |
| 53 | +**Basic Logging** |
| 54 | + |
| 55 | +```php |
| 56 | +// Log all ability executions. |
| 57 | +add_action( 'before_execute_ability', function( $ability_name, $input ) { |
| 58 | + error_log( 'Executing ability: ' . $ability_name ); |
| 59 | + if ( $input !== null ) { |
| 60 | + error_log( 'Input: ' . wp_json_encode( $input ) ); |
| 61 | + } |
| 62 | +}, 10, 2 ); |
| 63 | + |
| 64 | +add_action( 'after_execute_ability', function( $ability_name, $input, $result ) { |
| 65 | + error_log( 'Completed ability: ' . $ability_name ); |
| 66 | + error_log( 'Result: ' . wp_json_encode( $result ) ); |
| 67 | +}, 10, 3 ); |
| 68 | +``` |
0 commit comments