syntatis / wp-hook
WordPress hook with object-oriented programming
Requires
- php: ^7.4 || ^8.0
- syntatis/utils: ^1.0
Requires (Dev)
- dealerdirect/phpcodesniffer-composer-installer: ^1.0
- phpcompatibility/php-compatibility: ^9.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.6
- roots/wordpress: ^6.5
- symfony/var-dumper: ^5.4
- syntatis/coding-standard: ^1.1
- szepeviktor/phpstan-wordpress: ^1.3
- wp-phpunit/wp-phpunit: ^6.5
- yoast/phpunit-polyfills: ^2.0
README
🪝 wp-hookWordPress hook with object-oriented programming
A small class wrapper to allow using WordPress hooks with OOP, inspired from the WordPress Plugin Boilerplate, and added with a few syntactic features.
Why?
One common pitfall that I often encounter when managing a large complex site with the plugins and themes is that we could easily fall into nesting multiple hooks:
add_action( 'init', 'initialise' ); function initialise(): void { add_action( 'after_setup_theme', 'hello_world' ); } function hello_world(): void { echo 'Hello World'; }
The problem with the above example is that WordPress may never execute the hello_world
function since the after_setup_theme
would have already done executing before the init
hook. In some extreme cases, nested hooks may cause an error.
This library aims to help minimising this pitfall.
Installation
composer require syntatis/wp-hook
Usage
use Syntatis\WPHook\Hook; $hook = new Hook(); $hook->addAction( 'init', 'initialise' ); $hook->addFilter( 'after_setup_theme', 'hello_world' ); $hook->run();
If your WordPress theme or plugin is using PHP 8.0, you can use PHP Attributes to add the hooks.
use Syntatis\WPHook\Action; use Syntatis\WPHook\Filter; use Syntatis\WPHook\Hook; #[Action(tag: "wp")] class HelloWorld { #[Action(tag: "init")] public function initialise(): void { echo 'initialise'; } #[Filter(tag: "the_content", priority: 100)] public function content(string $content): string { return $content . "\ncontent"; } public function __invoke(): void { echo 'wp'; } } $hook = new Hook(); $hook->annotated(new HelloWorld()); $hook->run();