Last active
May 6, 2020 13:40
-
-
Save yousan/10b44cea1f3d66ee711cc7161e2d5a8a to your computer and use it in GitHub Desktop.
Change WordPress table prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Change WordPress table prefix | |
# WP-CLI is reqiured | |
# WARNING: BACKUP is strongly recommended | |
# usage: change_db_prefix.sh wp_new_prefix_ | |
# 1. Get all WordPress tables | |
# 2. Change wp_options and wp_usermeta values | |
# 3. Rename tables | |
# 4. Change table prefix at wp-config.php | |
PREFIX=`wp db prefix` | |
NEW_PREFIX=$1 | |
if [[ -z "$1" ]] ; then | |
echo 'No prefix is specified. Please specify new table prefix.' | |
exit; | |
fi | |
# Get all WordPress tables | |
# @see https://developer.wordpress.org/cli/commands/db/tables/ | |
TABLES=`wp db tables --all-tables-with-prefix` | |
# Change options and usermeta table value | |
wp search-replace ${PREFIX} ${NEW_PREFIX} ${PREFIX}options | |
wp search-replace ${PREFIX} ${NEW_PREFIX} ${PREFIX}usermeta | |
# Rename tables | |
# @see https://www.wpbeginner.com/wp-tutorials/how-to-change-the-wordpress-database-prefix-to-improve-security/ | |
IFS=$'\n' | |
for TABLE in ${TABLES} | |
do | |
NEW_TABLE=`echo ${TABLE} | sed -e 's/^'${PREFIX}'/'${NEW_PREFIX}'/'` | |
echo 'DROP TABLE IF EXISTS ' ${NEW_TABLE} | wp db cli # Remove tables | |
echo 'RENAME TABLE `'${TABLE}'` TO `'${NEW_TABLE}'`;' | wp db cli # Do RENAME here | |
done | |
# Change table prefix at wp-config.php | |
wp config set table_prefix ${NEW_PREFIX} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment