Never actually adding the action? Or do I have to call the action?
I have the following class that is instantiated in the
function.php
file. In the constructor I am setting up a activation and a deactivation hook for the theme. How ever neither seem to be called when I actually switch between this theme and say twenty fourteen and then back. As the echo statements are not called:
namespace Core;
class Activation {
protected $themeOptions = null;
public function __construct(){
if ($this->themeOptions === null) {
$this->themeOptions = \Freya\Factory\Pattern::create('Freya\Templates\Options');
}
if(is_admin()) {
echo 'Sample';
// On Activation ...
add_action('after_theme_switch', array($this, 'themeActivation'));
// On Deactivation ...
add_action('switch_theme', array($this, 'themeDeactivation'));
}
}
public function themeActivation(){
echo 'activated';
$this->setUpPluginOptions();
$this->installPlugins();
}
public function themeDeactivation(){
echo 'deactivated';
$this->themeOptions->deleteOptions(array (
'theme_options',
'plugin_management'
));
}
public function plugin_install_error_message() {
$this->themeOptions->renderView('plugin_install_error_message');
}
protected function installPlugins() {
if (!get_option('plugin_installed') && !get_option('plugin_install_error') && is_admin()) {
$pluginManagement = new \Core\Plugins\InstallPlugins();
$pluginManagement->installPlugins();
if (get_option('plugin_install_error')) {
add_action('admin_notices', array ($this, 'plugin_install_error_message'));
}
}
}
protected function setUpPluginOptions() {
$this->themeOptions->createOptions(
array (
'plugin_management' => array (
'plugin_installed',
'plugin_install_error',
'plugin_install_success',
)
)
);
}
}
The
echo Sample;
is called when the theme is activated. so I know its at least getting here. But the other
echo
s are not called.
Can some one tell me why the
add_action
is not doing what I want it to? do I have to call
do_action
?
is there something I am missing?
Solutions
You are using
after_theme_switch
action but the correct name is
after_switch_theme
.
Also, you won't see the echo statements on
after_theme_switch
and
switch_theme
. To debug things in that hooks you can use, for example,
error_log()
function and look for messages in PHP error
log file
(you need to have errors "On" and/or WP_DEBUG enabled).
I've tested this and it works:
new Activation;
class Activation {
public function __construct(){
add_action('after_switch_theme', array($this, 'themeActivation'));
add_action('switch_theme', array($this, 'themeDeactivation'));
}
public function themeActivation(){
error_log( 'activated' );
}
public function themeDeactivation(){
error_log( 'deactivated' );
}
}