Last active
March 16, 2022 11:56
-
-
Save OllieJones/a99819463aededbedaa8e9dddf27c59c to your computer and use it in GitHub Desktop.
Register WordPress Hooks Declaratively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace OllieJones; | |
use ReflectionClass; | |
use ReflectionMethod; | |
/** | |
* Automatically register WordPress hooks in classes derived from this one. | |
* | |
* Public methods with names starting with "action_" or "filter_" | |
* are automatically registered with WordPress on instantiation, | |
* and deregistered upon destruction. | |
*/ | |
class WordPressHooks { | |
private $actionPrefix; | |
private $filterPrefix; | |
private $priority; | |
private $methods; | |
protected function __construct( | |
$actionPrefix = 'action__', | |
$filterPrefix = 'filter__', | |
$priority = 10 ) { | |
$this->actionPrefix = $actionPrefix; | |
$this->filterPrefix = $filterPrefix; | |
$this->priority = $priority; | |
$this->register(); | |
} | |
protected function register() { | |
$reflector = new ReflectionClass ( $this ); | |
$this->methods = $reflector->getMethods( ReflectionMethod::IS_PUBLIC ); | |
foreach ( $this->methods as $method ) { | |
$methodName = $method->name; | |
$argCount = $method->getNumberOfParameters(); | |
if ( strpos( $methodName, $this->actionPrefix ) === 0 ) { | |
$hookName = substr( $methodName, strlen( $this->actionPrefix ) ); | |
add_action( $hookName, [ $this, $methodName ], $this->priority, $argCount ); | |
} else if ( strpos( $methodName, $this->filterPrefix ) === 0 ) { | |
$hookName = substr( $methodName, strlen( $this->filterPrefix ) ); | |
add_filter( $hookName, [ $this, $methodName ], $this->priority, $argCount ); | |
} | |
} | |
} | |
protected function unregister() { | |
foreach ( $this->methods as $method ) { | |
$methodName = $method->name; | |
$argCount = $method->getNumberOfParameters(); | |
if ( strpos( $methodName, $this->actionPrefix ) === 0 ) { | |
$hookName = substr( $methodName, strlen( $this->actionPrefix ) ); | |
remove_action( $hookName, [ $this, $methodName ], $this->priority ); | |
} else if ( strpos( $methodName, $this->filterPrefix ) === 0 ) { | |
$hookName = substr( $methodName, 0, count( $this->filterPrefix ) ); | |
remove_action( $hookName, [ $this, $methodName ], $this->priority ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment