Dynamically Load WordPress Database


The file wp-config.php defines configuration before WordPress is fully loaded, and includes things like database credentials and unique authentication keys. Did you know these configurations can dynamically be loaded? The following custom code will dynamically determine a database name based on an environment variable.

// Dynamically load DB per Captain ID
$captain_id = getenv('CAPTAIN_ID');
if ( ! empty( $captain_id ) ) {
	define( 'DB_NAME', "captaincore_cli_{$captain_id}" );
} else {
	define( 'DB_NAME', 'captaincore_cli_1' );
}

Multisite like mode using WP-CLI and shell variables

Giving the above code we can now dynamically determine which database to be loaded by changing the environment variable CAPTAIN_ID. In the command line that would be accomplished like this:

export CAPTAIN_ID=<new_id_here>

Now we can generate an entire new database using the same WordPress installation.

wp option get home
https://site1.test
export CAPTAIN_ID=2
wp option get home 
Error: Error establishing a database connection.
wp db create
Success: Database created.
wp core install --url=https://site2.test --admin_user=captaincore --admin_email=support@captaincore.io --title="CaptainCore"
Success: WordPress installed successfully.
wp option get home
https://site2.test

Similar to a multisite network, these two separate WordPress sites will share the same set of WordPress files. However, unlike multisite, these sites will have a completely separate databases which mean each site will simply operate like a standard WordPress site based on the current environment variable value.

In theory this could allow for a shadow copy website piggybacked off of a production website.

I’d imagine that you could expand this technique further to allow for an entirely hidden WordPress site piggybacked on an existing production website. If your host doesn’t allow for new databases then the same logic could be used to create sites through a unique $table_prefix. That’s not my intention, just an intriguing idea. I’m currently using this method within CaptainCore which uses a WordPress installation exclusively from WP-CLI.