Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

class class{}
$my_class = new class;
add_action('init', 'my_class');
share|improve this question
    
Have you looked at the example on the add_action codex page? –  Milo Dec 30 '12 at 16:54
    
See this answer for different possibilities. –  toscho Dec 30 '12 at 17:10

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Small and usefull answer. –  bueltge Dec 30 '12 at 17:24
2  
The first method doesn’t pass E_STRICT, and the last needs a good explanation. :) –  toscho Dec 30 '12 at 20:50
    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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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