wp-config.php and git

If you are storing your WordPress changes in git and then deploy the project between different machines (local, test server, production environment, etc), then you are probably familiar with a problem of wp-config.php file.  WordPress uses it for things like database credentials, which vary from machine to machine.  But you can’t just ignore the file since it’s plays the role in WordPress bootstrap.  The solution that we are using at work is very simple: have an additional configuration file, such as wp-config-local.php, which defines local settings, and which is ignored from git.

Here is how to do this.  First, you need to create the file itself.  Let’s say we want to change the database credentials which WordPress should use on the current machine.  Create a file wp-config-local.php with the following content:

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'localdev');
define('DB_PASSWORD', 'code15poetry');
define('DB_NAME', 'wp_playground');
?>

Now we need to include the file from the wp-config.php. The local configuration file should be optional, so we only use it on those machines that need it. Here is the code that I’ve added to the top of my wp-config.php:

// Load wp-config-local.php
$localConfig = dirname(__FILE__) 
    . DIRECTORY_SEPARATOR . 'wp-config-local.php';
if (file_exists($localConfig) && is_file($localConfig) 
    && is_readable($localConfig)) {
    require_once $localConfig;
}

If you will have a look at your WordPress website now, it’ll probably be broken. That’s because you are not allowed to redefine constants. We’ve defined that in our wp-config-local.php which loads first, and then they are defined in the wp-config.php as well. We should work around this. For any constant that is defined in wp-config.php and which you want to be able to set from wp-config-local.php, change the line in wp-config.php like so:

// before
// define('DB_USER', 'root');
// after
if (!defined('DB_USER')) { define('DB_USER', 'root'); }

With this, you’ll basically have values in wp-config.php act as defaults. If there is no local configuration, they will be used. Otherwise, the local ones will be utilized.

The last tiny bit that you need to do is add wp-config-local.php to your .gitignore file. That’s it. Now commit, push, and enjoy.

Leave a Comment