Last active
February 18, 2017 17:43
-
-
Save iambriansreed/ceb9f49ec9abbe54613c30cb8528d546 to your computer and use it in GitHub Desktop.
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 | |
/* | |
* tl;dr | |
* Adding `Helpers::add_hooks($this);` to your class constructor loads any needed add_action and add_filters hooks. | |
*/ | |
class Class_Helpers { | |
/** | |
* Takes in a class and parses each of the class' method names | |
* looking for action or filters and generating add_action or add_filters. | |
* | |
* A method named `action_init` would generate: | |
* add_action( 'init', array( $class_object, 'init' ), 10, 1 ); | |
* | |
* A method named `action_init_5_8` would generate: | |
* add_action( 'init', array( $class_object, 'init' ), 5, 8 ); | |
* | |
* If you include the priority you must include the accepted_args number. | |
* | |
* If you add the following in your class' constructor all needed | |
* add_action and add_filters calls are generated. | |
* | |
* Helpers::add_hooks( $this ); | |
* | |
* @param $class_object | |
*/ | |
public static function add_hooks( $class_object ) { | |
$method_names = get_class_methods( get_class( $class_object ) ); | |
foreach ( $method_names as $method_name ) { | |
$hook = self::parse_method( $method_name ); | |
if ( $hook && 'action' === $hook->type ) { | |
add_action( $hook->name, array( $class_object, $method_name ), $hook->priority, $hook->accepted_args ); | |
} | |
if ( $hook && 'filter' === $hook->type ) { | |
add_filter( $hook->name, array( $class_object, $method_name ), $hook->priority, $hook->accepted_args ); | |
} | |
} | |
} | |
public static function parse_method( $method_name ) { | |
$is_action = 0 === strpos( $method_name, 'action_' ); | |
$is_filter = 0 === strpos( $method_name, 'filter_' ); | |
if ( $is_action || $is_filter ) { | |
$method_name = substr( $method_name, 7 ); | |
$matches = array(); | |
preg_match( '/_\d+_\d+$/', $method_name, $matches ); | |
$priority = 10; | |
$accepted_args = 1; | |
if ( count( $matches ) ) { | |
list( $priority, $accepted_args ) = array_values( array_filter( explode( '_', $matches[0] ) ) ); | |
$method_name = substr( $method_name, 0, - 1 * strlen( $matches[0] ) ); | |
} | |
return (object) array( | |
'type' => $is_action ? 'action' : 'filter', | |
'name' => $method_name, | |
'priority' => $priority, | |
'accepted_args' => $accepted_args | |
); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment