5

So is it possible to do something like this with add_action?

class class{}
$my_class = new class;
add_action('init', 'my_class');
2
  • Have you looked at the example on the add_action codex page?
    – Milo
    Commented Dec 30, 2012 at 16:54
  • See this answer for different possibilities.
    – fuxia
    Commented Dec 30, 2012 at 17:10

3 Answers 3

5

You can do this:

class testclass {
  function test() {
    echo 'howdy';
  }
}
add_action('wp_head',array('testclass','test'));

Or this:

$t = new testclass();
add_action('wp_head',array($t,'test'));

It doesn't work like...

$t = new testclass();
add_action('wp_head','t');
// or this either, for good measure
$t = new testclass();
add_action('wp_head',array('t'));

.. but I am not sure what you are trying to accomplish by using that pattern. You've already instantiated the class so the constructor, if present, has already ran. Without a callback method, I don't know what you expect to happen.

2
  • 1
    Small and usefull answer.
    – bueltge
    Commented Dec 30, 2012 at 17:24
  • 2
    The first method doesn’t pass E_STRICT, and the last needs a good explanation. :)
    – fuxia
    Commented Dec 30, 2012 at 20:50
2
class MyPluginClass {

    public function __construct() {

         add_action( 'save_post', array( $this, 'myplugin_save_posts' ) );
    }

    public function myplugin_save_posts() {
         // do stuff here...
    }
}

$mypluginclass = new MyPluginClass(); 

check in Using Add Action In Your Class in WordPress Codex

2

In the (accepted) answer the first example is incorrect:

class testclass() {                             
    function test() {                             
        echo 'howdy';                               
    }                                             
}                                               
add_action( 'wp_head', array( 'testclass', 'test' ) );

It is incorrect because method test is not static.

The correct use for the static call in the action would be:

class testclass() {                             
    function static test() {                             
        echo 'howdy';                               
    }                                             
}                                               
add_action( 'wp_head', array( 'testclass', 'test' ) );

you could also write it then as:

add_action( 'wp_head', 'testclass::test' );
1
  • Could you edit your answer and show the correct use of the example? As it stands you're copy and pasting the code somebody else has provided where you could be writing an answer that shows proper use. Otherwise, I can clean this up and move it to the comment section.
    – Howdy_McGee
    Commented Jan 16, 2018 at 21:42

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.