kerryrandolph/wp-hook-annotations

Use PHP docblock @annotations to register WordPress hooks, filters and shortcodes

0.0.3 2019-06-05 13:42 UTC

This package is auto-updated.

Last update: 2024-04-06 00:36:50 UTC


README

Use PHP Docblock @annotations to register WordPress hooks, filters and shortcodes.

Latest Stable Version Total Downloads Latest Unstable Version License composer.lock

Requirements

  • PHP 7.2+
  • PHP-DI 6

Install

Via Composer

$ composer require kerryrandolph/wp-hook-annotations

Usage

Instead of wiring callbacks with boilerplate add_action(), add_filter(), or add_shortcode(), simply add the annotations directly to the callback function's docblock:

/**
  * @Action(tag="wp_loaded",priority=10,accepted_args=1)
  */
public function doSomething(){
  // do something
}

The following annotations can be used:

/**
 * @Action(tag="the_hook_name", priority=1, accepted_args=1)
 * @Filter(tag="the_filter_name", priority=1, accepted_args=1)
 * @Shortcode(tag="the_shortcode_name")
 */
  • The priority and accepted_args parameters are optional, and default to 10 and 1 respectively
  • Double quotes are required: tag="double_quoted". single quotes will throw an exception

Wire multiple hooks to a single callback function:

/**
  * @Filter(tag="some_wp_filter")
  * @Action(tag="some_wp_action")
  * @Filter(tag="another_wp_filter")
  */
public function updateSomeValue(string $value): string {
  return 'updated';
}

Once you have added the hook annotations, you need to get the HookManager object to process them.

If you are using Dependency Injection, the easiest way is by using the provided HookAware trait:

class MyWordpressHookClass {
  use HookAware;
  
  /**
    * @Action(tag="wp_loaded")
    */
  public function foo(){}
}

The HookAware->processHooks method is triggered automatically by the DI container, and uses reflection to discover the hooks and wire them into Wordpress.

Alternatively, you could get the HookManager in the constructor via DI, and manually trigger processHooks:

__construct( HookManager $hook_manager ) {
  $hook_manager->processHooks( $this );
}

License

WP Hook Annotations is released under the MIT License.