Register WordPress Hooks Declaratively

Have you ever written any WordPress code that needed to register a lot of hooks — a lot of actions and filters? Have you ever forgotten to put the right number of $expectedArgs into the call to add_action() or add_filter()? Worse, have you ever forgotten your call to one of those?

No more! This article is about a little abstract class called WordPressHooks (I thought of calling it WordPressHooker, but that might mean something I didn’t intend.) It lets us write php classes containing action and filter callbacks, and register them automatically. Here’s an example to define and use the 'wp_enqueue_scripts' action and the filter on 'the_title'.

<?php
class Demo extends \OllieJones\WordPressHooks {

  /** The constructor must invoke the parent constructor.
   *   The parent constructor calls add_filter() and add_action()
   */
  public function __construct() {
    parent::__construct();
  }

  /** Name your action callbacks "action__$hookname".
   * @return void
   */
  public function action__wp_enqueue_scripts() {
    wp_enqueue_style( 'plugin_name', 
                      plugin_dir_url( __FILE__ ) . 'css/adminstyle.css', [], '1.2.3',
                      'all' );
    wp_enqueue_script( 'plugin_name',
                       plugin_dir_url( __FILE__ ) . 'js/adminjs.js', [ 'jquery' ], '1.2.3',
                       false );
  }

  /** Name your filter callbacks "filter__$hookname".
   */
  function filter__the_title( $title ) {
    return 'The ' . $title . ' was filtered';
  }
}

The idea is simple. In this example, the filter hook is 'the_title‘. You can write your filter function with the name filter__the_title, and the WordPressHooks superclass will automatically register your function as a callback for that filter, providing the correct number of $accepted_args. It works the same way with action callbacks.

Here is the definition of the abstract class.

Leave a Comment