Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active September 12, 2017 23:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/340900ba153fa9c3b30b83f7b163210c to your computer and use it in GitHub Desktop.
Save tommcfarlin/340900ba153fa9c3b30b83f7b163210c to your computer and use it in GitHub Desktop.
[WordPress] Registering WordPress Hooks Using Another Class
<?php
add_action( 'plugins_loaded', 'acme_start' );
/**
* Start the machine.
* https://www.youtube.com/watch?v=ysoMOefPyRs
*/
function acme_start() {
$plugin = new AcmeColumn();
}
<?php
class AcmeColumn {
private $registry;
public function __construct( $registry ) {
$this->registry = $registry;
}
public function start() {
$registry->add_hook( 'filter', 'manage_edit-page_columns', $this, 'add_page_column' );
}
public function add_page_column( $page_columns ) {
$page_columns['template'] = 'Acme Column';
return $page_columns;
}
}
<?php
add_action( 'plugins_loaded', 'acme_start' );
/**
* Start the machine.
* https://www.youtube.com/watch?v=ysoMOefPyRs
*/
function acme_start() {
$registry = new HookRegistry();
$acme_column = new AcmeColumn( $registry );
$acme_column->start();
}
<?php
class HookRegistry {
public add_hook( $type, $name, $object, $method ) {
$type = strtolower( $type );
if ( 'filter' !== $type || 'action' !== $type ) {
return new WP_Error( '1', 'No proper hook type defined.' );
}
}
private function add_filter( $name, $object, $method ) {
add_filter( $name, array( $object, $method ) );
}
private function add_action( $name, $object, $method ) {
add_action( $name, array( $object, $method ) );
}
}
<?php
class HookRegistry {
private $registry;
public function __construct() {
$this->registery = array();
}
public add_hook( $id, $type, $name, $object, $method ) {
$type = strtolower( $type );
if ( 'filter' !== $type || 'action' !== $type ) {
return new WP_Error( '1', 'No proper hook type defined.' );
}
if ( 'filter' === $type ) {
$this->add_filter( $name, $object, $method );
} else {
$this->add_action( $name, $object, $method );
}
$hook_info = array(
$type,
$name,
$object,
$method,
);
$this->registry[ $id ] = $hook_info;
}
private function add_filter( $name, $object, $method ) {
add_filter( $name, array( $object, $method ) );
}
private function add_action( $name, $object, $method ) {
add_action( $name, array( $object, $method ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment