Reputation: 1727
This is a part of code that involved in my question:
class My_Box {
function __construct( $args ) {
add_action( 'admin_footer', array( __CLASS__, 'add_templates' ) );
}
static function add_templates() {
self::add_template( 'list' );
self::add_template( 'grid' );
}
private static function add_template( $name ) {
echo html('script',array( /*args*/));
}
}
The add_action in the above code requires the arguments to be string like this:
add_action('handle','function_name');
Now I need to run the add_action statement outside the class, I figured something like this:
add_action( 'wp_footer', My_Box::add_templates() );
This statement got a debug message of "Notice: Undefined offset: 0 ".
How to code this add_action statement correctly?
Upvotes: 0
Views: 1092
Reputation: 1732
Checkout this http://codex.wordpress.org/Function_Reference/add_action#Using_add_action_with_a_class
To use the add_action hook when your plugin or theme is built up using classes, add $this to your add_action call together with the function name within that class, like so:
class MyPluginClass
{
public function __construct()
{
//add your actions to the constructor!
add_action( 'save_post', array( $this, 'myplugin_save_posts' ) );
}
public function myplugin_save_posts()
{
//do stuff here...
}
}
Upvotes: 0
Reputation: 4021
The array you are passing as the second argument to add_action
is a callback. The first value in the array is the class name and the second is the name of a static method on that class. Within a class __CLASS__
will contain the name of that class. So to make this same call elsewhere you just need to replace that with the actual class name, e.g.
add_action( 'wp_footer', array('My_Box', 'add_templates' );
For more info on how callbacks are defined see: http://www.php.net/manual/en/language.types.callable.php
Upvotes: 0
Reputation: 13728
for fetching in class
add_action('handle', array(get_class(), 'function_name'));
outside of class
add_action('handle', array('class_name', 'func_name'));
Upvotes: 1