Skip to content

Instantly share code, notes, and snippets.

@sajdoko
Created April 19, 2023 12:44
Show Gist options
  • Save sajdoko/c5cce0af7e07ed18fefc2117dc639bda to your computer and use it in GitHub Desktop.
Save sajdoko/c5cce0af7e07ed18fefc2117dc639bda to your computer and use it in GitHub Desktop.
Bash script that performs the search and replace on each cPanel user's Wordpress page content using mysql command.
#!/bin/bash
# Loop through each WordPress installation directory under /home/*/public_html/
for dir in /home/*/public_html/; do
# Check if the directory contains a wp-config.php file
if [ -f "${dir}wp-config.php" ]; then
echo -e "Processing ${dir}"
# Get the database credentials from wp-config.php
DB_NAME=$(grep "define( 'DB_NAME'" ${dir}wp-config.php | cut -d "'" -f 4)
DB_USER=$(grep "define( 'DB_USER'" ${dir}wp-config.php | cut -d "'" -f 4)
DB_PASSWORD=$(grep "define( 'DB_PASSWORD'" ${dir}wp-config.php | cut -d "'" -f 4)
DB_HOST=$(grep "define( 'DB_HOST'" ${dir}wp-config.php | cut -d "'" -f 4)
TABLE_PREFIX=$(grep "\$table_prefix" ${dir}wp-config.php | cut -d "'" -f 2)
# echo -e ${DB_NAME}
# Connect to the database and perform the search and replace operation
mysql -u${DB_USER} -p${DB_PASSWORD} -h ${DB_HOST} -D ${DB_NAME} -e "UPDATE ${TABLE_PREFIX}posts SET post_content = REPLACE(post_content, 'old string', 'new string') WHERE (post_type = 'page' AND post_name IN ('first-page-slug', 'second-page-slug'));"
mysql -u${DB_USER} -p${DB_PASSWORD} -h ${DB_HOST} -D ${DB_NAME} -e "UPDATE ${TABLE_PREFIX}postmeta SET meta_value = REPLACE(meta_value, 'old string', 'new string') WHERE (meta_key = '_elementor_data' AND meta_value LIKE '%old string%');"
fi
done
@sajdoko
Copy link
Author

sajdoko commented Apr 19, 2023

Save the shell script (e.g. wp-search-replace.sh) and make it executable by running chmod +x wp-search-replace.sh.
You can then run the script by navigating to its directory in your terminal and running ./wp-search-replace.sh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment