Working with Classes and WordPress Filters and Actions

If you are like me, you love putting similar code together in a clean manner in classes. In some cases, OOP is Overworking Of PHP (smart, no?). In other cases, it saves a lot of time and repetition if you do this in an object oriented manner.

If you are making WordPress plugins, you always have to hook into wordpress’ functionalities using Filters or Actions. We usually do it this way:

add_filter('the_content','add_booyaa_after_content');
function add_booyaa_after_content($content) 
{
    $content .= 'Booyaa!!';
    return $content;
}

Now, it’s a small function. There is no need to do this in a ‘classy’ manner. But if you do, how would you tell wordpress to use that class methods?

Let’s say we have class named Booya:

class Booyaa
{
  
  function __construct()
  {
    # do something on boot
  }

  /**
   * Adds Booyaa after the content
   * Static function
   */
  public static function addAfter($content)
  {
    $content .= 'Booyaa!!';
    return $content;
  }

  /**
   * Adds Booyaa before the content
   * Not a static function. Class must be instanciated to use this;
   */
  public function addBefore($content)
  {
    return 'Booyaa!! ' . $content;
  }
}

 

So, we have two methods that we may use: addAfter and addBefore.

One is Static, one is public.

Now, you can easily use a static method like this:

add_filter( 'the_content', ['Booyaa', 'addAfter'] ); // static method. The first entry of the array is the class' name

But, it gets a little complicated when you want to use Instance methods.

You could try and instanciate the class in a function and deal with the matter. But if you want to keep the code clean, the best thing to do is have all your hooks and filters be registered withe the admin_init hook via the constructor or with a static initiation method.

Here’s how the static initiation would look like:

class Booyaa
{
  
  function __construct()
  {

  }

  public static function init()
  {
  	add_action( 'the_content', [ $this, 'addBefore' ] ); // hook up an instance method
  	add_action( 'the_content', [ __CLASS__ , 'addBefore' ] ); // hook up a static method
  }

  /**
   * Adds Booyaa after the content
   * Static function
   */
  public static function addAfter($content)
  {
    $content .= 'Booyaa!!';
    return $content;
  }

  /**
   * Adds Booyaa before the content
   * Not a static function. Class must be instanciated to use this;
   */
  public function addBefore($content)
  {
    return 'Booyaa!! ' . $content;
  }
}

// initialize on a plugin file or the php file itself
Booyaa::init();

That’s the basic idea of it. If you spot any mistakes, please feel free to let me know.

Scroll Up