syntatis/wp-hook

此包已废弃,不再维护。作者建议使用syntatis/codex包。

面向对象的WordPress钩子


README

Packagist Dependency Version wp codecov

注意

此包现在是Codex的一部分。

一个用于使用面向对象编程(OOP)的WordPress钩子的类包装器,灵感来源于WordPress插件模板。此类可以帮助您在管理WordPress插件或主题中的钩子时保持组织性和结构。

安装

通过Composer安装此包

composer require syntatis/wp-hook

使用

创建Registry类的新实例并注册您的钩子

use Syntatis\WPHook\Registry;

$registry = new Registry();
$registry->addAction('init', 'initialise');
$registry->addFilter('the_content', 'content', 100);
$registry->addAction('add_option', 'option', 100, 2);

使用PHP属性

如果您的主题或插件运行在PHP 8.0或更高版本,您可以使用PHP属性直接在类中定义钩子

use Syntatis\WPHook\Action;
use Syntatis\WPHook\Filter;
use Syntatis\WPHook\Registry;

#[Action(name: "wp")]
class HelloWorld
{
    #[Action(name: "init")]
    public function initialise(): void
    {
        echo 'initialise';
    }

    #[Filter(name: "the_content", priority: 100)]
    public function content(string $content): string
    {
        return $content . "\ncontent";
    }

    #[Action(name: "the_content", priority: 100, acceptedArgs: 2)]
    public function option(string $optionName, mixed $value): void
    {
        echo $optionName . $value;
    }

    public function __invoke(): void
    {
        echo 'wp';
    }
}

$registry = new Registry();
$registry->parse(new HelloWorld());

注意

属性只会应用于非抽象的公共方法,这些方法不是PHP原生方法,也不是以__开头的任何方法,例如__constructor__clone__callStatic。如果您在类级别添加属性,类应实现__invoke方法,如上面的示例所示。

移除钩子

您也可以像使用原生的WordPress函数那样移除钩子

$registry = new Registry();
$registry->addAction('init', 'initialise');
$registry->addFilter('the_content', 'content', 100);

// ...later in the code...
$registry->removeAction('init', 'initialise');
$registry->removeFilter('the_content', 'content', 100);

也可以一次性移除所有钩子

$registry = new Registry();
$registry->addAction('init', 'initialise');
$registry->addFilter('the_content', 'content', 100);

// ...later in the code...
$registry->removeAll();

可以将对象实例的方法、静态方法或闭包附加到钩子

use Syntatis\WPHook\Registry;

$helloWorld = new HelloWorld();
$anonymous = fn () => 'Hello, World!';

$registry = new Registry();
$registry->addFilter('the_content', [$helloWorld, 'content'], 100);
$registry->addAction('init', $anonymous);

但是,这会使在代码中稍后移除钩子变得相当复杂,因为您需要将相同的对象实例或相同的匿名函数引用传递给removeActionremoveFilter方法,这并不总是可能的。

为了解决这个问题,您可以将id传递给addActionaddFilter方法,并在移除钩子时使用@符号引用该id。例如

use Syntatis\WPHook\Registry;

$helloWorld = new HelloWorld();
$anonymous = fn () => 'Hello, World!';

$registry = new Registry();
$registry->addFilter('the_content', [$helloWorld, 'content'], 100, 1, ['id' => 'the-content-hello-world']);
$registry->addAction('init', $anonymous, 10, 1, ['id' => 'init-hello-world']);

// ...much later in the code...

$registry->removeAction('init', '@init-hello-world', 10);
$registry->removeFilter('the_content', '@the-content-hello-world', 100);

重要

ID必须全部小写,并使用由-._分隔的单词。它不应包含任何大写字母、空格或特殊字符。您可以使用斜杠(/)定义命名空间,例如acme/hello-world,以避免与其他插件或主题冲突。请注意,在注册表中添加的ID必须唯一。如果您尝试添加相同的ID两次,将抛出异常。

参考资料