loading...

6 October 2021

Create basic add_action() and do_action in class and function

To implant actions in classes, we need access to composer. As we already have access to the repository and the class autoloader is already loaded. We can create a class that performs an action hook in the constructor.

<?php

namespace Example;

class Example
{
  public function __construct()
  {
    add_action('example_hook', [$this, 'example_function'], 10, 1);
    // default is: 10 - priority, 1 - default value params
  }

  public function example_function($param)
  {
    return $param;
  }
}

Now in the constructor, due to the fact that it always executes when creating a class, we call a hook called “example_hook” to which we assign the function “example_function”. You can pass any number of parameters in the action. However, there is one condition for more than one condition in action. Look:

...

add_action('example_hook', [$this, 'example_function'], 10, 2);

// 10 - priority
// 2 - number of arguments
...

Now you can finally cling to your hook like this

<?php do_action('example_hook', ['param' => true]) ?>

You’re not using classes? Do it with a function. See how:

<?php

add_action('example_hook', 'example_function');

function example_function($param)
{
  return $param;
}

Posted in wordpress