kerryrandolph/wp-hook-annotations

使用PHP docblock @annotations来注册WordPress钩子、过滤器和短代码

0.0.3 2019-06-05 13:42 UTC

This package is auto-updated.

Last update: 2024-09-06 01:43:00 UTC


README

使用PHP Docblock @annotations来注册WordPress钩子、过滤器和短代码。

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

要求

  • PHP 7.2+
  • PHP-DI 6

安装

通过Composer

$ composer require kerryrandolph/wp-hook-annotations

用法

直接在回调函数的docblock中添加注解,而不是使用样板代码add_action()add_filter()add_shortcode()

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

以下注解可以使用

/**
 * @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")
 */
  • priorityaccepted_args参数是可选的,分别默认为10和1
  • 需要双引号:tag="double_quoted"。单引号将抛出异常

将多个钩子连接到单个回调函数

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

添加钩子注解后,您需要获取HookManager对象来处理它们。

如果您使用依赖注入,最简单的方法是通过提供的HookAware特质

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

HookAware->processHooks方法由DI容器自动触发,并使用反射来发现钩子并将它们连接到WordPress。

或者,您可以通过DI在构造函数中获取HookManager,并手动触发processHooks

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

许可证

WP Hook Annotations在MIT许可证下发布。