Matt Cohen

Renaming your WordPress plugin's main file without deactivating your plugin

by Matt Cohen in Tutorials, WordPress. 2 min read.

Renaming your WordPress plugin's main file without deactivating your plugin

WordPress stores a record of all active plugins in the options table as an array with the directory name and the main plugin filename as the unique identifier of the plugin. Sometimes, we make a spelling error in the main plugin filename and want to change that filename. If we do this, the plugin will be automatically deactivated by WordPress, which disrupts the user’s experience with the plugin.

Here’s a tip on how to rename the main plugin filename without your plugin being deactivated.

In our scenario, lets say we have our plugin directory as my-awesome-plugin and the filename as my-awesom-plugin.php. Note the spelling error in our filename. It is good practice to have the plugin filename match it’s directory name, so lets set about renaming the file.

To start, we’ll make a file with the correct name, and place our plugin header and plugin code in that file. This will be the file which all new installs use when activating our plugin.

We then have our old (incorrect) filename, and place a version of the following code in this file:

<?php
/**
 * Backwards compat.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$active_plugins = get_option( 'active_plugins', array() );
foreach ( $active_plugins as $key => $active_plugin ) {
    if ( strstr( $active_plugin, '/my-awesom-plugin.php' ) ) {
        $active_plugins[ $key ] = str_replace( '/my-awesom-plugin.php', '/my-awesome-plugin.php', $active_plugin );
    }
}
update_option( 'active_plugins', $active_plugins );

When an older installation of our plugin runs, the old incorrect filename will run, which triggers the above snippet. This code will run only once.

In this snippet, we retrieve a list of all active plugins from the database, loop through them and loop for our incorrect filename. We then replace it in the array with the correct filename, and update the active_plugins option in the database.

From now on, the plugin will load using the correct filename, and thus run our plugin code.

Over time, we can seek to remove this backwards compatibility file, once we’re certain the majority of our users are using a more recent version of our plugin.