So is it possible to do something like this with add_action?
class class{}
$my_class = new class;
add_action('init', 'my_class');
So is it possible to do something like this with add_action?
class class{}
$my_class = new class;
add_action('init', 'my_class');
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.
E_STRICT, and the last needs a good explanation. :)
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();
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' );