When developing WordPress sites I generally have three environments: live, staging, and local. Since I like my staging environment to be a very close replica of production, I frequently overwrite the database and files in staging. This is especially true when working with a host like WP Engine that has one-click staging environments.
However, when the database is overwritten in staging, there’s a generally a few settings that still need to be different from production. For instance, with WooCommerce sites, I may need to deactivate SSL and put Stripe into testing mode.
Occasionally I’ll also need to deactivate certain analytics plugins or third-party API integrations like MailChimp.
After making these updates manually for months, I finally moved to a programmatic update routine for many of my sites. The code basically just checks which environment we’re in. If it’s one of the staging environments and the update script hasn’t been run already, it runs it.
Update Routine Code
Here’s example code for the update routine, which I’ll explain in more detail underneath:
I used to have the script always run unless it detected it was in production, i.e.:
if ( 'https://example.com' == site_url() )
But I realized this could be dangerous if the site_url ever got updated on production by mistake. Explicitly setting the stage and local environments where the script should run seemed safer.
Use Transient to Check if Settings Updated
We don’t need the update routine to run constantly, just once after the database has been overwritten. We may even want to re-enable some of those plugins or change a setting back in order to test something specific in staging.
This is where the transient comes into play: get_transient( ‘staging-settings-updated’ ). A transient is basically an option that expires after a specific amount of time. In this case, if the transient has already been set, it means the update routine has run and we don’t need to run it again. For this example, I have the transient expire after a day- but you could set this as long as you like.