0

Is it possible to activate plugins per theme?

I have a multisite, and I know it is possible to activate plugins per site. But I need plugins to be enabled for specific themes.

Someone asked a similar question - if it is possible to activate plugins by other plugins: How To Activate Plugins via Code?

This was an accepted answer:

    //Activate a plugin programmatically - Akismet example

    function run_activate_plugin( $plugin ) {
    $current = get_option( 'active_plugins' );
    $plugin = plugin_basename( trim( $plugin ) );

    if ( !in_array( $plugin, $current ) ) {
        $current[] = $plugin;
        sort( $current );
        do_action( 'activate_plugin', trim( $plugin ) );
        update_option( 'active_plugins', $current );
        do_action( 'activate_' . trim( $plugin ) );
        do_action( 'activated_plugin', trim( $plugin) );
    }

    return null;
}
run_activate_plugin( 'akismet/akismet.php' );

However someone commented about this not being very safe and I'm also not sure if this would be a good idea to add to a theme's functions.php file.

I added this above code to a themes functions.php to activate some plugins and so far this is working without any problems. Would I run into problems with this, or is there some better code to use? There is also this function activate_plugin() not sure if that function is a better way to activate plugins.

I am no good with code, any help appreciated.

1 Answer 1

-1

Write This Code On theme Function.php

function run_activate_plugin( $plugin ) {
$current = get_option( 'active_plugins' );
$plugin = plugin_basename( trim( $plugin ) );

     if ( !in_array( $plugin, $current ) ) {
         $current[] = $plugin;
          sort( $current );
          do_action( 'activate_plugin', trim( $plugin ) );
          update_option( 'active_plugins', $current );
          do_action( 'activate_' . trim( $plugin ) );
          do_action( 'activated_plugin', trim( $plugin) );
       }

    return null;
 }
run_activate_plugin( 'plugin-folder-name/plugin-main-file.php' );

It's working

3
  • 1
    Can you explain a little as how it answers the OP in addition to the code posted ?
    – bravokeyl
    Jul 6, 2016 at 5:34
  • 1
    Thanks for your answer Vivek, and welcome to WPSE. Echoing what @bravokeyl said, if you could explain your code that would be fantastic. Code only answers are hard to understand and in the end don't actually teach people how to code :) There's an edit link below your post. Thanks!
    – Tim Malone
    Jul 6, 2016 at 5:52
  • only you can put this code in functions.php and replace plugin-folder-name with your plugin name and plugin-main-file.php with main plugin file name(index.php or plugin-file.php) Jul 6, 2016 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.