Created
January 18, 2012 01:29
-
-
Save mikeschinkel/1630212 to your computer and use it in GitHub Desktop.
Proposing an add_autohook_support() function for WordPress.
This file contains 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 | |
/** | |
* Simplifies addition of WordPress hooks to a class. | |
* | |
* @param string|object $target - Class name or instance of class | |
* @param array $methods - List of methods and their overrides. Array key is method name, value is false (don't use as hook), alternate hook name, alternate priority, or alternate hook name and priority: array($hook_name,$priority). | |
* | |
* Author: Mike Schinkel | |
* Author URI: http://about.me/mikeschinkel/ | |
*/ | |
function add_autohook_support( $target, $methods = array() ) { | |
/** | |
* @var ReflectionMethod $method | |
*/ | |
$class_reflector = new ReflectionClass( $target ); | |
foreach ( $class_reflector->getMethods( ReflectionMethod::IS_PUBLIC ) as $method ) { | |
$hook_name = $method->name; | |
$priority = 10; | |
if ( isset( $methods[$method->name] ) ) { | |
if ( false === ( $method_args = $methods[$method->name] ) ) | |
continue; | |
if ( is_string( $method_args ) ) { | |
$hook_name = $method_args; | |
} else if ( is_numeric( $method_args ) ) { | |
$priority = $method_args; | |
} else if ( is_array( $method_args ) ) { | |
list( $hook_name, $priority ) = $method_args; | |
} | |
} | |
add_filter( $hook_name, array( $target, $method->name ), $priority, $method->getNumberOfParameters() ); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment