In this article we're going to take a look at how to create a config file in WordPress that is compatible with multiple environments. The goal is to be able to deploy or upload all site files without worrying about breaking the code because you require different settings for different environments.
WordPress only has one configuration file by default titled 'wp-config.php' located in the root of your installation, let's take a quick look at what a section of this usually looks like:
/** The name of the database for WordPress */
/** MySQL database username */
/** MySQL database password */
/** MySQL hostname */
/** Database Charset to use in creating database tables. */
For one environment this is fine, but what if you want to work locally and / or deploy this code to a development or production server, then you're likely to need different settings (e.g. the database name or password). For this reason, usually you need to make sure you exclude this file each time you upload or deploy your code.
Wouldn't it be nicer if the config file automatically detected which settings to use depending on the environment?
Before we look at an example let's just go over the different varaiables that we might want to change between environments:
In the example below, we're going to create a config file that works for the following:
- Local - your local machine that may be running software such as WAMP or XAMMP, in this example the local environment has been set up with the '.dev' extension - yourdomain.dev
- Development - a test environment with the same configuration as live on a sub domain of 'dev.'
- Production - the live site
To create a config file compataible with multiple environments, we're going to pick up the domain name that the site is being accessed on to define which settings should be used. This can be achieved using the $_SERVER global by accessing the 'SERVER_NAME' variable. Let's take a look at an example:
If you want to point multiple domains to the same site code or intend on using subdomains, you'll also need to include these in the list. To save duplicating settings you can just use a fallthrough like so:
...and that's all there is to it, you can now deploy the same code to any environment and it will still work. You can add additional environments (e.g. staging) by adding another case statement. Also notice how in the local and development environments we've added the additional 'WP_DEBUG' to show notices while developing.
It's worth pointing out that this technique isn't exclusive to WordPress, by adapting the variables this same technique could be applied to other frameworks.