How to automate WordPress database synchronization?

Let's assume that you want to import the production database state to your local server. How to do this in a few steps?

tl;drGitHub

This topic is related to task automation so if you want to understand this example well, check out this or at least tools section that describes how to use those scripts.

Manual

- Download database backup from the server.
- Import SQL file.
- Use the SearchReplace to replace URLs from production to the local domain.
- Remove unnecessary accounts and keep only required.
- Change passwords for all accounts that have left.
- Remove unnecessary content (revisions, drafts, etc).
- Disable page visibility for bots in system settings.

Auto

As the website grows, this task becomes more time-consuming, making it a huge challenge. That's why I don't see any other option than automating this.

function db:anonimize() {
  wp option set blog_public 0

  LIST=$(wp user list --field=ID --exclude="1")
  if [ ! -z "$LIST" ]
  then
    wp user delete $LIST --reassign=1
  fi

  wp user update $(wp user list --field=ID) --user_pass=test1234 --skip-email
}

function db:import:prod() {
  db:import
  wp search-replace $DOMAIN_PROD $DOMAIN_LOCAL --all-tables
  db:anonimize
}

With the script I just need to perform two simple steps to synchronize the database.

  1. Download the database backup and put it in the document root.
  2. Run the ./wp.sh db:import:prod task.

The system will perform all required actions for me.

Feedback

How satisfied you are after reading this article?