WP Search-Replace: WordPress Migration & Serialized Data

Migrate WordPress domains safely with wp search-replace. Preserve PHP serialized data, skip post GUIDs, update Elementor CSS, and avoid broken layouts.

WP Search-Replace: WordPress Migration & Serialized Data
WordPress Migration CLI Runbook

To run a safe WordPress database migration with wp search-replace: Back up your database using wp db export,[2] preview edits with wp search-replace 'https://old-domain.com' 'https://new-domain.com' --all-tables --skip-columns=guid --dry-run,[1] re-run without --dry-run once verified, and flush caches with wp cache flush.[6]

Follow this engineering runbook to execute deterministic WordPress domain and protocol migrations over SSH while preserving PHP serialized arrays, JSON payloads, and page builder stylesheets.[1][3]

Why Raw SQL Corrupts WordPress Serialized Data (And How wp search-replace Fixes It)

WordPress themes, widgets, and page builders store structured arrays and objects inside wp_options and wp_postmeta using PHP’s serialize() byte-stream format.[3][4] Each serialized string records its exact byte length directly inside the payload, such as s:22:"https://old-domain.com";.[3][4]

Running a blind SQL UPDATE with REPLACE() or editing a .sql dump in a text editor changes the domain string without updating the integer byte count.[3] When WordPress calls unserialize(), the mismatched byte count causes deserialization to fail, silently wiping widget configurations, theme options, and menu layouts.[3][4]

WP-CLI wp search-replace prevents this failure because it is serialization-aware.[1] By default, it runs fast SQL queries on plain-text columns and automatically switches to PHP unserialization, string replacement, length recalculation, and re-serialization whenever it encounters serialized data—while also matching JSON-escaped URLs such as https:\/\/old-domain.com.[1]


WP-CLI wp search-replace Flags and Migration Method Comparison

Selecting the right execution mode in wp search-replace balances migration speed, nested object accuracy, and rollback safety on production databases.[1]

Migration Method Serialization & JSON Handling Speed Profile Primary Key & GUID Safety Recommended Use Case
Raw SQL UPDATE ... REPLACE() Corrupts PHP serialized byte counts Fastest (pure MySQL/MariaDB) Modifies any column unless filtered Never use on wp_options or wp_postmeta[3]
wp search-replace (Default Mode) Uses SQL on plain columns, auto-switches to PHP for serialized data; handles JSON slashes[1] Fast on large wp_posts tables Skips primary keys; pair with --skip-columns=guid[1] Standard single-site and staging-to-live migrations
wp search-replace --precise Forces PHP processing across every column, including complex nested serialized structures[1] Slower than SQL default mode[1] Preserves primary keys and object recursion[1] Complex page builders, WooCommerce meta, and nested objects
wp search-replace --export=file.sql Processes replacements in PHP/SQL and writes a clean SQL dump without touching the live DB[1] Moderate (bounded by disk I/O and --export_insert_size=50)[1] Safe read-only generation from source database[1] Generating pre-migrated SQL dumps for remote server imports

Step-by-Step WordPress Migration Runbook Using wp search-replace

When migrating high-traffic WordPress stores onto Nextgen Hosting Dedicated Servers or low-latency Pakistan Dedicated Servers, executing migrations over SSH with WP-CLI eliminates browser timeouts and PHP upload limits.[1][3]

Step 1: Export a Full Database Backup

Navigate to your WordPress document root (the directory containing wp-config.php) and export a point-in-time SQL backup before altering any table.[2] wp db export invokes mysqldump or mariadb-dump using the credentials defined in wp-config.php.[2]

# Move to your WordPress root directory
cd /home/username/public_html

# Export a timestamped backup using wp-config.php credentials
wp db export pre-migration-backup.sql

Confirm the SQL file exists and is non-zero in size before proceeding.

Step 2: Run a Dry Run Preview Across All Tables

Execute wp search-replace with --dry-run to inspect every affected table and replacement count without modifying database rows.[1] Pair --all-tables (to cover custom plugin tables outside $wpdb) with --skip-columns=guid so existing RSS feed item identifiers remain intact.[1]

# Preview replacements without writing to the database
wp search-replace 'https://staging.example.pk' 'https://example.pk' \
  --all-tables \
  --skip-columns=guid \
  --precise \
  --dry-run

If you only want to target tables sharing the active site prefix in a shared database, substitute --all-tables-with-prefix in place of --all-tables.[1]

Step 3: Execute the Live Replacement

Once the --dry-run table counts match expectations, remove --dry-run to commit the replacement.[1]

# Execute live serialized-safe replacement across all tables
wp search-replace 'https://staging.example.pk' 'https://example.pk' \
  --all-tables \
  --skip-columns=guid \
  --precise
Pro Tip

Run Protocol Normalization Separately if Needed: If legacy posts still reference http://example.pk while staging used https://staging.example.pk, run a second pass for 'http://example.pk' to 'https://example.pk'. Avoid trailing slashes in both search and replace arguments unless targeting a specific subdirectory path.

Step 4: Update Elementor URLs and Regenerate CSS Files

Page builders such as Elementor maintain static CSS bundles inside /wp-content/uploads/elementor/css/ that retain old asset URLs even after database rows update.[5] Run Elementor’s native WP-CLI subcommands immediately after wp search-replace:[5]

# Update Elementor internal page URLs
wp elementor replace-urls 'https://staging.example.pk' 'https://example.pk'

# Delete stale CSS caches and regenerate stylesheets immediately
wp elementor flush-css --regenerate

Step 5: Flush Object Cache and Rewrite Rules

Stale persistent object cache entries (Redis or Memcached) and outdated .htaccess rules often serve old URLs after migration. Flush both layers using WP-CLI:[6]

# Clear persistent object cache (Redis / Memcached)
wp cache flush

# Flush WordPress rewrite rules and update .htaccess on single-site installs
wp rewrite flush --hard

Note that wp rewrite flush --hard only updates .htaccess when mod_rewrite is declared in your wp-cli.yml or config.yml under apache_modules.[6]

Common Pitfall: Enabling --log or --regex on Multi-Gigabyte Databases
Passing --regex makes wp search-replace approximately 15-20x slower and disables automatic JSON slash matching.[1] Similarly, passing --log introduces a severe performance penalty equal to or worse than --precise or --regex.[1] Reserve --log for targeted debugging on individual tables such as wp_options rather than full database sweeps.[1]


Handling Edge Cases: Multisite, Hyphens, Missing Primary Keys, and Complex Migrations

Production databases frequently contain edge cases that cause partial replacements or skipped rows if overlooked.[1]

  1. Tables Without a Primary Key: WP-CLI intentionally skips any database table lacking a primary key.[1] Inspect table schemas with wp db query 'DESCRIBE wp_custom_table' and verify PRI appears in the Key column before relying on wp search-replace.[1]
  2. Strings Starting With -- or Empty Replacements: Positional arguments beginning with double hyphens confuse CLI option parsing.[1] Use explicit flags instead: wp search-replace --old='--legacy-token' --new=''.[1]
  3. WordPress Multisite Networks: By default, wp search-replace touches only the primary site tables registered to $wpdb.[1] Pass --network alongside --url=old-network.com (and optionally --skip-tables=wp_users) to migrate all network subsites safely.[1]
  4. Hardcoded wp-config.php Constants: If WP_HOME or WP_SITEURL are explicitly defined in wp-config.php, update or remove those constants after running wp search-replace so WordPress reads the migrated database options cleanly.[3]

Step-by-Step Migration Verification Checklist

Run through this numbered verification checklist after every WordPress migration:

  1. Database Backup Confirmed: Verify pre-migration-backup.sql exists outside the public web root or delete it after verification so no SQL dump remains downloadable over HTTP.[2]
  2. Dry-Run Count Audited: Confirm --dry-run output matched expected rows across wp_options, wp_posts, wp_postmeta, and custom tables.[1]
  3. Core URLs Verified: Run wp option get home && wp option get siteurl to confirm both return the exact target https:// domain without trailing slashes.[3]
  4. Page Builder CSS Rebuilt: Confirm wp elementor flush-css --regenerate completed with zero permission errors on /wp-content/uploads/elementor/css/.[5]
  5. Object & Page Caches Flushed: Confirm wp cache flush and wp rewrite flush --hard succeeded, then inspect page headers in an incognito browser session.[6]

Frequently Asked Questions About wp search-replace

Why does wp search-replace preserve serialized data while raw SQL breaks it?

PHP’s serialize() format encodes exact byte lengths alongside every string (such as s:22:"https://old-domain.com").[3][4] Raw SQL REPLACE() modifies the domain characters without updating the byte count, causing unserialize() to fail and discard settings, whereas wp search-replace unserializes the payload, swaps the string, recalculates lengths, and re-serializes cleanly.[1][3]

Should I use –all-tables or –all-tables-with-prefix in wp search-replace?

Use --all-tables-with-prefix when multiple applications or WordPress installs share a single database so only tables matching your $table_prefix are modified.[1] Use --all-tables on dedicated single-site databases when third-party plugins create custom tables that do not follow the standard prefix or $wpdb registration.[1]

Why should I pass –skip-columns=guid during a WordPress migration?

WordPress stores a permanent Globally Unique Identifier (guid) for every post to help RSS and Atom feed readers track whether an item has already been fetched.[1] Changing guid values during a domain migration causes feed subscribers to receive duplicate notifications for every historical post.[1]

When is the –precise flag needed with wp search-replace?

By default, wp search-replace uses fast SQL queries and switches to PHP automatically only when it detects serialized data in a column.[1] Passing --precise forces PHP processing across all columns, which runs slower but handles complex or deeply nested serialized data structures more reliably.[1]

How do I fix broken Elementor layouts after running wp search-replace?

After completing wp search-replace, run wp elementor replace-urls 'https://old-domain.com' 'https://new-domain.com' followed by wp elementor flush-css --regenerate.[5] This updates Elementor’s internal URL references and rebuilds static CSS files under /wp-content/uploads/elementor/css/.[5]


Migrate High-Traffic WordPress Sites Without Bottlenecks

Eliminate shared hosting limits, slow database imports, and PHP timeouts. Deploy full SSH root access, enterprise NVMe storage, and isolated network uplinks with Nextgen Hosting.

Explore Global Dedicated Servers Explore Pakistan Dedicated Servers

Disclaimer: This post is for informational and educational purposes only, accurate to the best of our knowledge at publication. It does not constitute advice. We do not guarantee accuracy or completeness and accept no liability for any decisions or losses resulting from reliance on this content.

Sources & Official References
  1. WordPress Developer Resources. "wp search-replace — WP-CLI Command Reference (--dry-run, --all-tables, --all-tables-with-prefix, --skip-columns, --precise, --recurse-objects, --export, --regex)." WordPress.org. Available at: https://developer.wordpress.org/cli/commands/search-replace/
  2. WordPress Developer Resources. "wp db export — WP-CLI Command Reference." WordPress.org. Available at: https://developer.wordpress.org/cli/commands/db/export/
  3. WordPress Developer Resources. "Migrating WordPress — Advanced Administration Handbook (Site URL, Serialized Data, Domain Changes)." WordPress.org. Available at: https://developer.wordpress.org/advanced-administration/upgrade/migrating/
  4. PHP Group. "serialize — Generates a storable representation of a value." PHP Manual. Available at: https://www.php.net/manual/en/function.serialize.php
  5. Elementor Developers. "Elementor CLI — replace-urls and flush-css Commands." Elementor.com. Available at: https://developers.elementor.com/docs/cli/replace-urls/ and https://developers.elementor.com/docs/cli/flush-css/
  6. WordPress Developer Resources. "wp cache flush and wp rewrite flush — WP-CLI Command References." WordPress.org. Available at: https://developer.wordpress.org/cli/commands/cache/flush/ and https://developer.wordpress.org/cli/commands/rewrite/flush/

Disclaimer: This post is for informational and educational purposes only, accurate to the best of our knowledge at publication. It does not constitute advice. We do not guarantee accuracy or completeness and accept no liability for any decisions or losses resulting from reliance on this content.