I'm going deep with oop to create wordpress plugins. I've found an interesting article about the hooks and how to use them inside a class. After reading I have some doubt: is correct to use the hooks inside the construcor or it's better to use a method instead of the constructor? What's the best practice to define a filter or an hook inside a class?

  • If you're declaring the filter inside a method, you just need to use the array format, with $this as an argument: apply_filters( 'filter_name', array( $this, 'function_name', 10, 1 ); Jan 11, 2020 at 15:18
  • 1
    I usually use the add_filter. The point of the question is what's the best approach to call hooks and filter in a class, If inside a method or in the construct of the class
    – sialfa
    Jan 11, 2020 at 15:21
  • 1
    add_filter and apply_filter do different things. apply_filter declares filters allowing devs to use add_filter. Having said that, the same applies. Just use the array as a second argument: add_filter( 'filter_name', array( $this, 'method_name' );. If you're asking whether you should declare a hook in the constructor or a method, then that's up to you, I guess. If you need to declare on instantiation of the class, you could use $this->declare_hooks(); insde the constructor, then public function declare_hooks() { add_hook('some', array($this, 'method'); } Jan 11, 2020 at 15:45
  • public function declare_hooks() { add_action('some', array($this, 'method'); } even Jan 11, 2020 at 15:51
  • Andy, you’re completely missing that point of the question. They’re not asking about how callbacks work in classes. They’re asking about where they should be defined within a class. Jan 11, 2020 at 16:08

2 Answers 2


No, constructors should not define hooks.

Constructors should be used to set the initial state of the object. Hooks have nothing to do with the object's initial state, so they don't belong in the constructor. Constructors should not have "side effects", so that using new ClassName() does not affect any other parts of the program, which is what registering hooks does.

A good overview of this issue is this article by Tom McFarlin. It also offers an alternative.


it depends on what you want to do. for example, suppose your plugin needs javascript for it to work. in this case, we can enqueue the javascript in the constructor of the Class :

class My_Plugin{

     function __construct (){

         add_action( 'wp_enqueue_scripts', array( $this , 'my_script' ) );


     function my_script(){

        // here you use the wp_enqueue_script(  );


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.