Why activate_plugin is not working in register_activation_hook

I am trying to activate second plugin automatically while activating first plugin.

register_activation_hook(__FILE__, 'example_activation' );
function example_activation() {
        include_once(ABSPATH .'/wp-admin/includes/plugin.php');
        activate_plugin('hello.php');
}

Its not working inside register_activation_hook..
Its working if i use it directly like:

include_once(ABSPATH .'/wp-admin/includes/plugin.php');
activate_plugin('hello.php');

How can i fix it? Thanks for help

Solution:

I am using this for myself now:

// When this plugin activate, activate another plugin too.
register_activation_hook(__FILE__, function(){
    $dependent="hello.php";
    if( is_plugin_inactive($dependent) ){
        add_action('update_option_active_plugins', function($dependent){
            /* for some reason, 
            activate_plugin($dependent); 
               is not working */
            activate_plugin('hello.php');
        });
    }
}); 

// When this plugin deactivate, deactivate another plugin too.
register_deactivation_hook(__FILE__, function(){
    $dependent="hello.php";
    if( is_plugin_active($dependent) ){
        add_action('update_option_active_plugins', function($dependent){
            deactivate_plugins('hello.php');
        });
    }
}); 

2 s
2

For full explanation of what’s happening see this post (this is for deactivating plug-ins, but the problem is the same).

A brief explanation: Plug-ins are essentially activated by adding them to the array of active pug-ins stored in the database. When you activate the first plug-in, WordPress retrieves the array of all currently active plug-ins, adds the plug-in to it (but doesn’t update the database yet) and then runs your installation callback.

This installation callback runs your code.

After that WordPress updates the database with the above array, which contains the first but not the second plug-in. Thus your second plug-in appears not be activated.

Solution: has mentioned in the above link the solution is something like this (untested):

//This goes inside Plugin A.
//When A is activated. activate B.
register_activation_hook(__FILE__,'my_plugin_A_activate'); 
function my_plugin_A_activate(){
    $dependent="B/B.php";
    if( is_plugin_inactive($dependent) ){
         add_action('update_option_active_plugins', 'my_activate_dependent_B');
    }
}

function my_activate_dependent_B(){
    $dependent="B/B.php";
    activate_plugin($dependent);
}

Leave a Comment