Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Daniel Dvorkin
- // Based on code by Ryan McCue
- class WPPlugin_Base {
- public static function _register_hooks($parent) {
- $prefixes = array('filter' => 'filter_', 'action' => 'action_');
- $self = new ReflectionClass($parent);
- foreach ($self->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
- $params = $method->getNumberOfParameters();
- $hooks = array('filter' => array(), 'action' => array());
- if ($prefixes['filter'] === '' || $prefixes['action'] === '') {
- $hooks['filter'][$method->name] = apply_filters($method->name . '_priority', 10);
- }
- elseif ($enable_prefixes === true && strpos($method->name, $prefixes['filter']) === 0) {
- $hook = substr($method->name, strlen($prefixes['filter']));
- $hooks['action'][$hook] = apply_filters($method->name . '_priority', 10);
- }
- elseif ($enable_prefixes === true && strpos($method->name, $prefixes['action']) === 0) {
- $hook = substr($method->name, strlen($prefixes['action']));
- $hooks['action'][$hook] = apply_filters($method->name . '_priority', 10);
- }
- foreach ($hooks['filter'] as $hook => $priority) {
- call_user_func(array($parent, 'add_filter'), $hook, $method->name, $priority, $params, $parent);
- }
- foreach ($hooks['action'] as $hook => $priority) {
- call_user_func(array($parent, 'add_action'), $hook, $method->name, $priority, $params, $parent);
- }
- }
- }
- }
- class WPPlugin extends WPPlugin_Base {
- protected function __construct() {
- $this->_register_hooks( $this);
- }
- protected function add_filter($hook, $method = null, $priority = 10, $params = null) {
- if ($method === null) {
- $method = $hook;
- }
- elseif (is_int($method)) {
- $priority = $method;
- $method = $hook;
- }
- if (!method_exists($this, $method)) {
- throw new InvalidArgumentException('Method does not exist');
- }
- if ($params === null) {
- $ref = new ReflectionMethod($this, $method);
- $params = $ref->getNumberOfParameters();
- }
- return add_filter($hook, array($this, $method), $priority, $params);
- }
- protected function add_action($hook, $method = null, $priority = 10, $params = null) {
- if ($method === null) {
- $method = $hook;
- }
- elseif (is_int($method)) {
- $priority = $method;
- $method = $hook;
- }
- if (!method_exists($this, $method)) {
- throw new InvalidArgumentException('Method does not exist');
- }
- if ($params === null) {
- $ref = new ReflectionMethod($this, $method);
- $params = $ref->getNumberOfParameters();
- }
- return add_action($hook, array($this, $method), $priority, $params);
- }
- }
- class Example extends WPPlugin {
- public function __construct() {
- parent::__construct();
- }
- public function action_init($a) {
- echo 'init!';
- }
- public function filter_the_content_priority(){ return 3; }
- public function filter_the_content($content){
- return $content;
- }
- }
- $plugin = new Example();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement