Features Pricing Docs Blog Log In Get Started Free

Search and Replace in Database

Safe Search and Replace with WP-CLI

Database search-and-replace is needed when migrating domains, switching from HTTP to HTTPS, or changing URLs. WP-CLI handles serialized data correctly, which is critical for WordPress.

Why Not Just Use SQL?

WordPress stores serialized PHP arrays in the database (e.g., widget settings, theme options). A simple SQL REPLACE breaks serialized data because it changes the string length without updating the length prefix. WP-CLI’s search-replace handles this correctly.

Dry Run First (Always)

sudo wp search-replace "http://old-domain.com" "https://new-domain.com" --dry-run --path=/home/DOMAIN/public_html --allow-root

This shows exactly how many replacements would be made in each table without changing anything.

Run the Replacement

sudo wp search-replace "http://old-domain.com" "https://new-domain.com" --path=/home/DOMAIN/public_html --allow-root

Common Use Cases

Scenario Old Value New Value
Domain change http://old.com https://new.com
HTTP to HTTPS http://example.com https://example.com
Staging to production https://staging.example.com https://example.com
WWW to non-WWW https://www.example.com https://example.com

Useful Flags

# Only search specific tables
sudo wp search-replace "old" "new" wp_posts wp_postmeta --path=$WP --allow-root

# Skip specific tables
sudo wp search-replace "old" "new" --skip-tables=wp_users --path=$WP --allow-root

# Export SQL instead of modifying in place
sudo wp search-replace "old" "new" --export=migration.sql --path=$WP --allow-root

# Case-insensitive (use regex)
sudo wp search-replace "Old-Domain\.com" "new-domain.com" --regex --regex-flags=i --path=$WP --allow-root

After Replacement

  1. Flush the cache: sudo wp cache flush --path=$WP --allow-root
  2. Flush Redis: redis-cli FLUSHALL
  3. Clear LSCache: sudo rm -rf /tmp/lscache/DOMAIN/
  4. Verify the site loads correctly
  5. Check for mixed content warnings in the browser console

Backup First

Always backup before search-replace:

sudo wp db export /home/DOMAIN/backup-$(date +%Y%m%d).sql --path=$WP --allow-root