Don’t hesitate to contact us if you have any feedback.

WordPress – Updating site URL with WP-CLI

A common task for WordPress developers is to migrate a site from a production environment to a local development environment. One of the crucial steps in this process is updating the URLs in the database to reflect the local environment. This can be efficiently achieved using WP-CLI, the command-line interface for WordPress.

Prerequisites

  • WP-CLI Installed: Ensure that WP-CLI is installed on your local machine. You can follow the official installation guide if needed.
  • WordPress Installed Locally: Make sure you have a local instance of WordPress running.
  • Database Backup: Always take a backup of your database before making any changes.

Step-by-Step Guide

1. Get the Production Database

The first step is to export the production database and import it into your local environment. Make sure you back up your local database before proceeding.

Export the Production Database:

# SSH into your production server and run:
wp db export /path/to/production-db.sql

Import the Database into Local Environment:

# On your local machine, navigate to your WordPress root directory and run:
wp db import /path/to/production-db.sql

2. Script to Replace URLs

Below is a script that automates the process of replacing the production URL with the local URL in the WordPress database. This script can run in two modes: Dry Run (test mode) and Live Run (actual replacement).

#!/bin/sh

LOCAL=your-website.com # WARNING !! without "local."
PROD=your-website-but-in-production.com # WARNING !! without "www."

yellow='\033[0;33m'
blue='\033[0;34m'
no_color='\033[0m'

# Test if you have wp-cli installed with composer
if test -f vendor/bin/wp.bat; 
then
  PREFIX=vendor/bin/wp.bat
else
  PREFIX=wp
fi

if [ "$1" == "live" ]
then
    MODE_STR="Live run"
    COLOR=$yellow
    QUESTION=no
    echo -e "${COLOR}"
else
    MODE=--dry-run
    MODE_STR="Dry run"
    COLOR=$blue
    QUESTION=yes

    echo -e "${COLOR}"
    echo -e "Starting Search and Replace DB in TEST Mode (Dry Run) in 5 seconds..."
    sleep 5
fi

echo ""
echo -e "========================================================================================================="
echo "Replacing admin email with: your-email@foo.com"
$PREFIX option update admin_email your-email@foo.com
echo -e "========================================================================================================="

echo ""
echo -e "========================================================================================================="
echo '   [WP Search Replace] '$MODE_STR' - Replace: https://www.'$PROD' => http://local.'$LOCAL
echo -e "=========================================================================================================${no_color}"
$PREFIX search-replace https://www.$PROD http://local.$LOCAL --all-tables $MODE

echo ""
echo -e "${COLOR}========================================================================================================="
echo '   [WP Search Replace] '$MODE_STR' - Replace: http://www.'$PROD' => http://local.'$LOCAL
echo -e "=========================================================================================================${no_color}"
$PREFIX search-replace http://www.$PROD http://local.$LOCAL --all-tables $MODE

echo ""
echo -e "${COLOR}========================================================================================================="
echo '   [WP Search Replace] '$MODE_STR' - Replace: https://'$PROD ' => http://local.'$LOCAL
echo -e "=========================================================================================================${no_color}"
$PREFIX search-replace https://$PROD http://local.$LOCAL --all-tables $MODE

echo ""
echo -e "${COLOR}========================================================================================================="
echo '   [WP Search Replace] '$MODE_STR' - Replace: http://'$PROD ' => http://local.'$LOCAL
echo -e "=========================================================================================================${no_color}"
$PREFIX search-replace http://$PROD http://local.$LOCAL --all-tables $MODE

echo ""
echo -e "${COLOR}========================================================================================================="
echo '   [WP Search Replace] '$MODE_STR' - Replace: //www.'$PROD ' => //local.'$LOCAL
echo -e "=========================================================================================================${no_color}"
$PREFIX search-replace //www.$PROD //local.$LOCAL --all-tables $MODE

if [ "$QUESTION" == "yes" ]
then
    while true; do
        echo -e "${blue}Above is the result of the test (Dry Run).${yellow}"
        read -p "Do you want to proceed to Live run? This action is irreversible! (yes/no) " yn
        echo -e "${no_color}"
        case $yn in
            yes ) echo -e "${yellow}Ok, let's go! Starting Search and Replace DB in Live Run in 5 seconds...${no_color}"; sleep 5; npm run wp:dbreplace -- live
                break;;
            no ) echo exiting...;
                exit;;
            * ) echo invalid response;
        esac
    done
    echo -e "${yellow}[WP Search Replace] Finished${no_color}"
fi

3. Adding the Script to Your Project

You can copy and paste the script into a file (e.g., search-replace-db.sh) inside a scripts folder at the root of your WordPress project.

Example Directory Structure:

/your-wordpress-project
|-- /scripts
|   |-- search-replace-db.sh
|-- /wp-content
|-- /wp-admin
|-- /wp-includes
|-- composer.json
|-- package.json
|-- wp-config.php

4. Adding WP-CLI via Composer

Ensure that WP-CLI is available via Composer. Add the following to your composer.json file:

{
  "require-dev": {
    "wp-cli/wp-cli-bundle": "v2.10.0"
  }
}

Then run:

composer install

If you don’t add WP-CLI via Composer, the script executed via npm will not work because it relies on the vendor/bin/wp.bat executable.

5. Adding a Command to package.json

If you have a package.json file at the root of your project, you can add a custom script to run the URL replacement script.

Example package.json script:

{
  "scripts": {
    "wp:dbreplace": "bash scripts/search-replace-db.sh"
  }
}

6. Running the Script

You can now run the script using npm:

For a Dry Run (Test Mode):

npm run wp:dbreplace

For a Live Run:

npm run wp:dbreplace -- live

This setup allows you to easily switch between testing and live replacements, ensuring that you don’t accidentally make irreversible changes to your database.

Conclusion

Using WP-CLI to replace URLs in your WordPress database is a powerful way to ensure smooth migrations between environments. By automating this process with a script, you can save time and reduce the risk of errors. Always remember to back up your database before making any changes, and test thoroughly using the Dry Run mode before proceeding to a Live Run.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *