There are a million ways to setup your WordPress site locally and another million for deploying to production and if you work on multiple sites at once, that creates another issue as well. All frameworks and CMSs like CodeIgniter or WordPress have some sort of database configuration file and you might have run into issues where that database config file needs to be reworked once you get the app or site into production. Adjusting configurations in production is a bad idea (a topic for another post), you want to take every possible step to get your site 100% production-ready locally, then deploy.
Image may be NSFW.
Clik here to view.
If you work with multiple sites in your local environment, then your site root directory is probably full of folders containing sites and apps, many of those being WordPress installs. One simple file can make a lot of difference and keep your deployments clean. If you place a file in your site root (locally) and call it something like local (no extensions or anything) and then just leave that file empty, you can reference it in your code. There are many ways to “sniff” out your environment with PHP or JavaScript, but I prefer to keep my code as lean as possible and use this method. If you take a look at the figure to the left, you can see the “local” file placed in your site root. Then if you open up your WP install and navigate to the wp-config.php file you can set up a conditional PHP statement to do a check to see if that file exists, if it does then load your local database configuration, if it does not, then load your production settings (you could extend this and load up staging setting as well).
You COULD place this local file in the site directory itself and look for it there, then if you’re using something like Git you could exclude the file with .gitignore, but since I work on many sites at once, some WordPress and some CodeIgniter, I prefere to keep the file in the root so that it is always there for me to reference. The conditional statement is below for you to check out, just replace the database settings in your wp-config.php with this snippet, fill out your environment credentials and you’re good to go.
I enjoy this method but I’m also aware of many other options to accomplish this same task, I’d love to hear thoughts in the comments.
if ( file_exists( dirname( __FILE__ ) . '/../local' ) ) { // Local Environment define('WP_ENV', 'local'); define('WP_DEBUG', true); define('DB_NAME', 'local_db_name'); define('DB_USER', 'local_db_user'); define('DB_PASSWORD', 'XXXXXXXXXXXX'); define('DB_HOST', 'localhost'); } else { define('WP_ENV', 'production'); define('WP_DEBUG', false); //Production Environment define('DB_NAME', 'prod_db_name'); define('DB_USER', 'prod_db_user'); define('DB_PASSWORD', 'XXXXXXXXXXX'); define('DB_HOST', 'prod_db_host'); }