Automate WordPress. One Script at a Time.

Search & Replace URLs

Safely replace all instances of a staging or old domain with the new live URL. This version runs a dry run first, giving you a chance to verify what will change before applying it.

#!/bin/bash

# === Configuration ===
WP_PATH="/var/www/html"                          # Path to your WordPress install
OLD_URL="https://staging.example.com"
NEW_URL="https://www.example.com"

# === Navigate to the WP install directory ===
cd "$WP_PATH" || { echo "❌ Error: WP path not found"; exit 1; }

# === Step 1: Dry run to preview changes ===
echo "🔍 Running dry run search-replace..."
wp search-replace "$OLD_URL" "$NEW_URL" \
  --all-tables \
  --precise \
  --recurse-objects \
  --skip-columns=guid \
  --dry-run

echo ""
read -p "Do you want to proceed with the actual replacement? (y/n): " CONFIRM

if [[ "$CONFIRM" != "y" ]]; then
  echo "❌ Replacement aborted."
  exit 0
fi

# === Step 2: Perform the actual search-replace ===
echo "⚙️ Performing live replacement..."
wp search-replace "$OLD_URL" "$NEW_URL" \
  --all-tables \
  --precise \
  --recurse-objects \
  --skip-columns=guid

echo "✅ URL replacement complete."
How to Create and Execute This Script

Follow these steps to create and run your WordPress script:

Open Your Terminal

Connect to your server via SSH or open your local terminal.

Create the Script File

Use a text editor like nano to create a new file. For example:

Paste the Script Code

Copy the full script from above and paste it into the terminal. Once done:

  • Press CTRL+O to save
  • Press Enter to confirm the filename
  • Press CTRL+X to exit nano

Make the Script Executable

Run the Script

⚠️ Backup First!

Use our handy script to run a full backup prior to using this script.

Requirements

  • WP-CLI must be installed and accessible from the shell.
  • wp-config.php must be correctly configured (WP-CLI uses it to access the DB).
  • Run this script as a user with permission to access the WP directory and write to the backup folder.