Quick & Dirty Multi-Environment WordPress Setup

WordPress is not a nice piece of software to work with. Especially if you need to deploy it in multiple environments. There are a couple of ways around this. The Bedrock stack that the Roots team have been working on proposes a solution. There is good solution over at SitePoint too, which is similar to the quick and dirty version I’m showing you here.

If you’re just looking for an easy way to have the same WordPress codebase interact with different databases in different environments then this is a solution for you.

First you need to set up an environment variable that WordPress can read. If you’re using Apache2 add the following line to your virtual host config file:

SetEnv WP_ENV local

Next open up wp-config.php and add this line of code above the database-related define statements:

$env = getenv('WP_ENV') ?: 'local';

If you’re running PHP < 5.3 (you shouldn't be, but you are already using WordPress) then change it to this:

$env = getenv(‘WP_ENV’) ? getenv(‘WP_ENV’) : ‘local’;

You can use any environment name you want as the default. I prefer local.

Then you just need to throw a switch statement around the DB settings that vary between environments. You'll end up with something like this:

switch ($env) {
    case 'local':
        define('DB_NAME', '...');
        define('DB_USER', '...');
        define('DB_PASSWORD', '...');
        break;
    case 'development':
        define('DB_NAME', '...');
        define('DB_USER', '...');
        define('DB_PASSWORD', '...');
        break;
}

If you end up using a remote database in production then update the statement when you add the connection details:

switch ($env) {
    case 'local':
        define('DB_NAME', '...');
        define('DB_USER', '...');
        define('DB_PASSWORD', '...');
        define('DB_HOST', 'localhost');
        break;
    case 'development':
        define('DB_NAME', '...');
        define('DB_USER', '...');
        define('DB_PASSWORD', '...');
        define('DB_HOST', 'localhost');
        break;
    case 'production':
        define('DB_NAME', '...');
        define('DB_USER', '...');
        define('DB_PASSWORD', '...');
        define('DB_HOST', 'fancy.remote.database');
        break;
}

And that's pretty much it. Quick, dirty and beautifully suited for WordPress. However if you need to vary more information than this between environments I would definitely recommend a more robust approach.