The problem came up recently about how to make sure plugins activated in the WordPress plugin UI don’t get deactivated if they are necessary for a site to function. I thought that was an interesting thought puzzle worth spending 15 minutes on, so I came up with this function as a solution:
function dt_force_plugin_active( $plugin ) {
add_filter( 'pre_update_option_active_plugins', function ( $active_plugins ) use ( $plugin ) {
// Match if properly named: wp-plugin (wp-plugin/wp-plugin.php).
$proper_plugin_name = $plugin . '/' . $plugin . '.php';
<pre><code> if (
file_exists( WP_PLUGIN_DIR . '/' . $proper_plugin_name )
&amp;&amp; is_file( WP_PLUGIN_DIR . '/' . $proper_plugin_name )
&amp;&amp; ! in_array( $proper_plugin_name, $active_plugins, true )
) {
$active_plugins[] = $proper_plugin_name;
return array_unique( $active_plugins );
}
// Match if improperly named: wp-plugin/cool-plugin.php.
if (
file_exists( WP_PLUGIN_DIR . '/' . $plugin )
&amp;&amp; is_file( WP_PLUGIN_DIR . '/' . $plugin )
&amp;&amp; ! in_array( $plugin, $active_plugins, true )
) {
$active_plugins[] = $plugin;
return array_unique( $active_plugins );
}
return array_unique( $active_plugins );
}, 1000, 1 );
Code language: PHP (php)
Which can be activated in your theme’s functions.php
like so:
dt_force_plugin_active( 'akismet' );
or dt_force_plugin_active( 'wordpress-seo/wp-seo.php' );
The only downside that I’ve seen so far is that you still get the Plugin deactivated.
message in the admin notices.
Leave a Reply