Last active
August 13, 2019 18:48
-
-
Save ethanclevenger91/af58269a5ca33af434d2509488bc7f96 to your computer and use it in GitHub Desktop.
An abstract class for wrapping related WP hooks together. For code organization.
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 | |
/** | |
* Usage: | |
* | |
* class RelatedHooks extends Hooks { | |
* | |
* private $actions = []; | |
* private $filters = []; | |
* | |
* } | |
* | |
* new RelatedHooks(); | |
* | |
*/ | |
abstract class Hooks { | |
/** | |
* Actions and filters are arrays of arrays, as follows: | |
* | |
* [ | |
* 'hook' => string, the WordPress hook to attach to | |
* 'callback' => string, object method or WordPress magic function | |
* 'priority' => (optional) int, the hooks priority | |
* 'args' => (optional) int, argument count | |
* ] | |
* | |
* For more details, see https://developer.wordpress.org/plugins/hooks/actions/ | |
* | |
*/ | |
protected $actions = []; | |
protected $filters = []; | |
public function __construct() { | |
$this->hook('actions'); | |
$this->hook('filters'); | |
return $this; | |
} | |
private function hook( $type ) { | |
foreach( $this->$type as $args ) { | |
// Callback must be defined | |
if( empty( $args['callback'] ) || empty( $args['hook'] ) ) continue; | |
$hook = $args['hook']; | |
// Allow for WordPress magic function | |
$callback = ( $args['callback'] == '__return_false' ?: [ $this, $args['callback'] ] ); | |
// Priority and argument count defaults | |
$priority = ($args['priority'] ?? 10); | |
$args_count = ($args['args'] ?? 1); | |
if( $type == 'actions') { | |
$this->addAction( $hook, $callback, $priority, $args_count ); | |
} | |
else if( $type == 'filters') { | |
$this->addFilter( $hook, $callback, $priority, $args_count ); | |
} | |
} | |
} | |
private function addAction( $hook, $callback, $priority, $args_count ) { | |
return add_action( $hook, $callback, $priority, $args_count ); | |
} | |
private function addFilter( $hook, $callback, $priority, $args_count ) { | |
return add_filter( $hook, $callback, $priority, $args_count ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment