Luminus
2/18/2018 - 2:04 PM

Clone an existing local WordPress site to a new folder. You must be using Laravel Valet or Valet+ as your local development environment

Clone an existing local WordPress site to a new folder. You must be using Laravel Valet or Valet+ as your local development environment

#!/bin/bash

# Function to display usage instructions when the command is used incorrectly
function usage {
	echo "usage: wp-clone <source> <destination>"
	echo "<source> is the site you want to clone"
	echo "<destination> is where you want to clone it to"
	exit 1
}

# Styles for displaying messages
VP_NONE='\033[00m'
VP_RED='\033[01;31m'
VP_GREEN='\033[01;32m'
VP_YELLOW='\033[01;33m'
VP_PURPLE='\033[01;35m'
VP_CYAN='\033[01;36m'
VP_WHITE='\033[01;37m'
VP_BOLD='\033[1m'
VP_UNDERLINE='\033[4m'

# Sites Constant. Decided to DRY up the code since there were a bunch of `~/www/sites/ calls`
# Most sane people use `~/Sites` by the way
cd ~/www/sites
SITES=`pwd`

# Make sure there are at least 2 arguments passed to the wp-clone command
# If the command is run with less than 2 arguments display usage instructions
if [[ -z "$1" ]] || [[ -z "$2" ]]; then
    usage
fi

# If the destination folder already exists you might be clobbering an existing site
# I could set up a flag to allow intentionally overwriting it but I never do this
if [[ -d "$SITES/$2" ]]; then
	echo -e "${VP_RED}Error:${VP_NONE} $SITES/$2 already exists"
	exit 1
fi

# Change current directory to Sites
cd $SITES

# Create destinaton directory
mkdir $2

# Copy files from source to destination
cp -a $1/. $2

# Export source db
cd $1
wp db export $1.sql

# Navigate to destination
cd $SITES/$2

# Change db name to <destination site name> in wp-config.php
# If you're using the default wp valet dbname values you'll want to replace `$1` and `$2` with `wp_$1` and `wp_$2`
search=$1
replace=$2
sed -i '' "s/${search}/${replace}/g" wp-config.php

# Create db from values in wp-config.php
wp db create

# Import source db
wp db import $SITES/$1/$1.sql

# Delete source db export file
rm $SITES/$1/$1.sql

# Find and replace URLs
wp search-replace //$1.test //$2.test

# Secure the site
valet secure $2

# Launch the site in default browser
valet open $2

# Launch the site's /wp-admin/ in your default browser
wp admin