Skip to main content
3 of 6
deleted 159 characters in body
emersonthis
  • 1.4k
  • 8
  • 20
  • 33

How to use add_action for multiple instances of the same class

I'm writing a plugin which defines a class that is meant to be called multiple times. The class uses add_action to register it's own methods as callbacks.

class MyClass {

    __construct($foo) {

        add_action('hook1', array($this, 'method1') );
        add_action('hook2', array($this, 'method2') );

    }

    public function method1() {...}

    public function method2() {...}

}

This works just fine. But when I do it twice, only the second works.

new MyClass('foo');
new MyClass('bar');

In other words, the results of the code above are exactly what I'd expect from the following:

// new MyClass('foo');
new MyClass('bar');

It seems like the second instance overrides the first. What am I doing wrong?

More information

This issue does appear to be linked to the way Wordpress registers actions. I'm currently on Wordpress v3.8.1 and I'm looking in /wp-includes/plugin.php. I see that when I register an action with add_action() (line 360) it is basically just a wrapper for add_filter() (line 82) which creates a unique $idx by calling _wp_filter_build_unique_id() (line 774). When I add debug code to print out the $idx, I see that it is in fact the same for both instances of my class. So it is confirmed that the subsequent instances of my class ARE overriding the previous(s). The remaining question is how to write my class so that this problem doesn't happen.

emersonthis
  • 1.4k
  • 8
  • 20
  • 33