Skip to main content

Add WordPress hook

Developing with WordPress will certainly require you to add hooks in order to modify the basic behavior. With Simply it is possible to add hooks in different ways :

Using PHP attribute

PHP 8 add internal attribute. Simply have two attributes to add filter or action.

<?php

namespace MyPlugin;

use Simply\Core\Attributes\Action;

class SimpleHook {
#[Action('init')]
public function myInit() {
}
}

Using a class implement an interface (deprecated)

By implementing HookableInterface you need to implement register function. In this function add all hooks you want to add. The service container automatically call this function after WordPress is setup.

<?php

namespace ClementCore\Hook;

use Simply\Core\Contract\HookableInterface;

class Excerpt implements HookableInterface {
public function register() {
add_action('excerpt_length', function($length) {
if (is_home()) {
return 20;
}
return $length;
});

add_action('excerpt_more', function($more) {
if (is_home()) {
return '...';
}
return $more;
});
}
}

Automatically register hook class

Simply can register hooks automatically :

  • If you register your plugin with registerPlugin function the class has automatically register
  • You can register your class as hook service by added service tags "wp.hook"
services:
ClementCore\Admin\Admin:
tags: ['wp.hook']

ClementCore\Api\OnLiveEndpoint:
tags: ['wp.hook']

Using dependency injection in Hook class

caution

A hook class is instanciated on each request. Be carefull and use Service Subscribers & Locators if you want to use dependency injection with hook classes.

<?php

namespace ClementCore\Api;

use Simply\Core\Contract\HookableInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;

class OnLiveEndpoint implements HookableInterface, ServiceSubscriberInterface {
use ServiceSubscriberTrait;

#[Action('rest_api_init')]
public function registerEndpoint() {
// ...
}

// ...

public function getTokenGenerator(): TokenGenerator {
return $this->container->get(TokenGenerator::class);
}

public static function getSubscribedServices(): array {
return [TokenGenerator::class => TokenGenerator::class];
}
}