syntatis/wp-hook

WordPress hook with object-oriented programming

v2.0.0 2024-05-12 10:11 UTC

This package is auto-updated.

Last update: 2024-05-12 10:13:27 UTC


README

🪝 wp-hook

WordPress hook with object-oriented programming

Packagist Dependency Version wp codecov

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();

References