cloakwp/hook-modifiers

使用修饰符扩展 WordPress 钩子,以实现更细粒度的过滤和操作

0.0.3 2024-09-09 22:57 UTC

This package is auto-updated.

Last update: 2024-09-09 22:57:27 UTC


README

WP Hook Modifiers 是一个 WordPress 插件/Composer 包,允许您通过“修饰符”扩展现有钩子,从而实现更细粒度的过滤和操作。

例如,如果您曾经使用过 ACF 钩子,您可能熟悉具有类似 acf/format_value 过滤器的修饰符,如 nametype,允许您通过名称或类型定位到特定字段(例如,acf/format_value/name=my_field_nameacf/format_value/type=image)。此包使您能够轻松创建类似 ACF 的自定义钩子修饰符,无论您是插件/主题开发者,还是希望扩展他人插件或主题的开发者。

安装

您可以通过 Composer 安装此包

composer require cloakwp/hook-modifiers

使用方法

use CloakWP\HookModifiers;

// Apply desired modifiers to an existing hook
HookModifiers::make(['post_type']) // note it accepts an array of multiple modifiers
  ->forFilter('wp_insert_post_data')
  ->register();

// Now you can use the modifier when calling the hook to target a specific post type
add_filter('wp_insert_post_data/post_type=page', function ($data, $postarr, $unsanitized_postarr) {
  $data['post_title'] = 'Page: ' . $data['post_title'];
  return $data;
}, 10, 2);

// The post_type example above is equivalent to:
add_filter('wp_insert_post_data', function ($data, $postarr, $unsanitized_postarr) {
  if ($data['post_type'] === 'page') {
    $data['post_title'] = 'Page: ' . $data['post_title'];
  }
  return $data;
}, 10, 2);

需要注意的是,修饰符必须是传递给过滤器的值之一中的属性键。在上面的示例中,我们知道 post_type 是被过滤的 data 数组(第 1 个参数)的属性。默认情况下,我们检查第一个钩子参数以查找修饰符键/值对,但可以通过调用 modifiersArgPosition 方法来更改这一点。例如,如果过滤器有 3 个参数,修饰符键/值对位于第三个参数中,您将这样做

HookModifiers::make(['type'])
  ->forFilter('some_filter_with_many_args')
  ->modifiersArgPosition(2) // 0 indexed, so the third arg is `2`
  ->register();

add_filter('some_filter_with_many_args/type=image', function ($one, $two, $three) {
  // This filter will only run if the arg $three is an associative array with a property 'type' equal to 'image'
}, 10, 3);

类似于 forFilter,还有一个 forAction 方法用于将修饰符应用于操作钩子。

注意:您必须调用 HookModifiers 对象的 register 方法才能实际将修饰符应用于钩子。