Created
January 18, 2025 18:35
-
-
Save bacoords/7e4034bdb48dea15f37f55e60cd700dc to your computer and use it in GitHub Desktop.
Pull production database and wp-content into your local environment with WP-CLI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Configuration variables - replace with your values | |
REMOTE_HOST="[email protected]" | |
REMOTE_PATH="files" | |
LOCAL_PATH="wp-content" | |
# Database name | |
TIMESTAMP=$(date +%Y%m%d_%H%M%S) | |
DB_BACKUP="wp_backup_${TIMESTAMP}.sql" | |
# Site URLs for search-replace | |
REMOTE_SITE_URL="productionurl.com" | |
LOCAL_SITE_URL="localurl.test" | |
# Check if required commands exist | |
command -v wp >/dev/null 2>&1 || { echo "WP-CLI is required but not installed. Aborting." >&2; exit 1; } | |
# Connect to remote server and export database | |
echo "Exporting remote database..." | |
wp db export files/wp-content/"$DB_BACKUP" --ssh="$REMOTE_HOST" --path="$REMOTE_PATH" | |
if [ $? -ne 0 ]; then | |
echo "Failed to export remote database. Aborting." | |
exit 1 | |
fi | |
# Sync wp-content directory, but exclude cache and backup files | |
echo "Syncing wp-content directory..." | |
rsync -avz --progress \ | |
--exclude='cache/' \ | |
--exclude='uploads/cache/' \ | |
--exclude='plugins/spinupwp/' \ | |
--exclude='backup-*/' \ | |
--exclude='*.log' \ | |
--exclude='debug.log' \ | |
--exclude='object-cache.php' \ | |
--exclude='.DS_Store' \ | |
--delete \ | |
"${REMOTE_HOST}:${REMOTE_PATH}/wp-content/" \ | |
"${LOCAL_PATH}/" | |
if [ $? -ne 0 ]; then | |
echo "Error: Failed to sync wp-content directory" | |
exit 1 | |
fi | |
# Remove remote backup file | |
ssh $REMOTE_HOST "rm $REMOTE_PATH/wp-content/$DB_BACKUP" | |
# Import the database locally | |
echo "Importing database to local environment..." | |
cd "$LOCAL_PATH" | |
wp db import "$DB_BACKUP" | |
if [ $? -ne 0 ]; then | |
echo "Failed to import database. Backup file is still available at $LOCAL_PATH/$DB_BACKUP" | |
exit 1 | |
fi | |
wp search-replace "$REMOTE_SITE_URL" "$LOCAL_SITE_URL" --all-tables | |
wp cache flush | |
# Cleanup local backup file | |
rm "$DB_BACKUP" | |
echo "Database sync completed successfully!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work.
My IDE's ShellCheck tool has recommended a couple of improvements. Feel free to ignore them, but I wanted to share them.
Line 22, 42 and 54: Check exit code directly with e.g. if mycmd;, not indirectly with $?. (see SC2181)
Line 48: Note that, unescaped, this expands on the client side. (specifically the $REMOTE_PATH variable, see SC2029)