I would like to deactivate a plugin for a specific user. I’m using the following code inside a the wp-content/plugin-mu
plugin file:
add_filter( 'option_active_plugins', 'bo_disable_apm_plugin' );
function bo_disable_apm_plugin( $plugins ) {
global $current_user;
// Not use advanced page manager for media manager
if ( is_admin() && in_array( 'media_manager', $current_user->roles ) ) {
$key = array_search( 'advanced-page-manager/advanced_page_manager.php' , $plugins );
if ( false !== $key ) {
unset( $plugins[$key] );
}
}
return $plugins;
}
Of course, it’s not working. I don’t understand the way option_active_plugins
. By dumping data, I find out the code is executed 7 times.
On the first loop, the user is not know, so the condition is not met. The plugin is still activated.
I have added a more complicated code with three conditionnal : unset the plugin if the user is not set, so the plugin is inactivated each time on the first loop. IF the user is set (next loops), check him to set/unset the plugin accordingly. Wasn’t working either.
I didn’t manage to find the right formula, so maybe I’m wrong somewhere and it can’t be done. Each time, the plugin is either activated or deactivated for all users. It looks like the first iteration is the one that counts.
Is there a way to inactivate a plugin for specific user/group ?
2 s
I think the answer to this Disable plugin / plugin action via theme is good for base knowledge on how to disable plugins from code.
Adapting that knowledge to your needs will leave us with this:
add_action('admin_init', 'my_filter_the_plugins');
function my_filter_the_plugins()
{
global $current_user;
if (in_array('media_manager', $current_user->roles)) {
deactivate_plugins( // deactivate for media_manager
array(
'/advanced-page-manager/advanced_page_manager.php'
),
true, // silent mode (no deactivation hooks fired)
false // network wide
);
} else { // activate for those than can use it
activate_plugins(
array(
'/advanced-page-manager/advanced_page_manager.php'
),
'', // redirect url, does not matter (default is '')
false, // network wise
true // silent mode (no activation hooks fired)
);
}
}
Basically this happens:
For the media_manager
user group the my_filter_the_plugins
disables(silently) the advanced-page-manager
plugin. We then need to reactivate the plugin(silently, again) for those that aren’t in the media_manager
user group.