Skip to content

07. Hooking with $hooker

Vlado Bosnjak edited this page Apr 18, 2024 · 3 revisions

Hooker

Hooker is used to streamline usage of add_filter and add_action. Read inline comments for more details in includes/class-hooker.php.

Usage:

$hooker->add_action( 'init', $php_class, 'method_to_call' );

Add multiple hooks at once

$hooker->add_actions([
    ['init', $php_class, 'method_to_call'],
    ['init', $php_class, 'another_method_to_call'],
    ['template_redirect', $php_class], // Will fire: $php_class->template_redirect() (See Note below)
]);

Note If your method name is same as hook name, you don't need to manually specify hook. Filters work same as action $hooker->add_filter / $hooker->add_filters

Adding hooks from within class

namespace MyBookShelf\Library;

class Book {

	// Main plugin instance.
	protected static $instance = null;

	public function __construct() {

		// Main plugin instance.
		$instance = \MyBookShelf\plugin_instance();
		$hooker   = $instance->get_hooker();

		// Admin hooks.
		$hooker->add_action( 'init', $this, 'do_something' );
	}

	/**
	 * This method will be called
	 */
	public function do_something() {

		// Your PHP code
	}
}

new Book;

Adding hooks from outside of the class

// Get main plugin instance
$instance = \MyBookShelf\plugin_instance();

// Get hooker
$hooker = $instance->get_hooker();

// Instantiate your class
$book = new \MyBookShelf\Library\Book();

// Add action or filter
$hooker->add_action('init', $book, 'do_something', 123, 3 );