Activate WordPress plugin with PHP code

Once in a while I come across a situation where I need to activate a plugin programatically rather than doing from the dashboard. Today’s issue was a session conflict on Pantheon, caused the WP Native PHP Sessions to crash and de-activate. Without that plugin active, I couldn’t get to the dashboard, so I wrote this code to re-activate the plugin and it did the trick.

You can paste this code into your functions.php or any PHP file that is required by your plugin/theme.

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( 'your-plugin-directory/your-plugin-main-file.php' );