Reputation: 22684
I want to run a function when my theme is activated. I have to add the theme activation hook within a php class:
final class My_Class_Name {
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self;
self::$instance->actions();
} else {
throw new BadFunctionCallException(sprintf('Plugin %s already instantiated', __CLASS__));
}
return self::$instance;
}
// some code
add_action('after_switch_theme', array( $this, 'activate' ));
function activate() {
// some code
}
// more code
}
My_Class_Name::getInstance();
When I activate my theme I get the following php error:
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'My_Class_Name' does not have a method 'activate' in /Applications/MAMP/htdocs/wp-themes/test/wp-includes/class-wp-hook.php on line 288
If I use add_action('after_switch_theme', 'activate' );
I get
PHP Fatal error: Cannot access self:: when no class scope is active
How can I make the hook work?
Upvotes: 0
Views: 756
Reputation: 1477
Here a simple way i made it work.
final class My_Class_Name {
// some code
public function __construct(){
add_action('after_switch_theme', array( $this, 'activate' ));
}
public function activate() {
file_put_contents(__DIR__.'\de.log','TEST');
}
// more code
}
new My_Class_Name();
Here is another way you can instantiate.
class My_Class_Name{
protected static $instance = null;
public function __construct(){}
public static function get_instance() {
// If the single instance hasn't been set, set it now.
if ( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
}
My_Class_Name::get_instance();
Upvotes: 1