I’m working on a large redesign project where lots of database changes are going to take place. In order to not mix-up the current master branch with the new redesign changes, I made a new database so I can keep things separate. The only trick is to remember to change out the database in wp-config.php when I switch branches.

That’s not going to happen. I’ll definitely forget. Regularly.

Fortunately, you can grab the branch you’re on via php with a bit of code from user program247365 on stackoverflow.

I took that and added a bit to choose the database I want based on the branch I’m on. You’ll need to change out the $db_name and $branch variables to match your own, then you’ll be good to go!


// get branchname
function config_get_git_branch() {
    // This assumes you have your .git directory at the same level as wp-config.php.
    // If you don't, then change the path to wherever your .git director is
    $stringfromfile = file('.git/HEAD', FILE_USE_INCLUDE_PATH);

    $firstLine = $stringfromfile[0]; //get the string from the array

    $explodedstring = explode("/", $firstLine, 3); //seperate out by the "/" in the string

    $branch = $explodedstring[2]; //get the one that is always the branch name

    return trim($branch);
}

// choose which db you want to use
function config_get_db_name() {
    $branch = config_get_git_branch();

    // change these $db_name and and $branch strings to match
    // whatever ones you want.
    if($branch === 'child') {
        $db_name = 'child_db';
    } else {
        $db_name = 'site_db';
    }
    return $db_name;
}

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', config_get_db_name());

Now you’ll never forgot to switch the DB out when you checkout to a new branch. Happy coding!