Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 15:09
Show Gist options
  • Save knolaust/49fab69c68ab810cad2b02ebc23db03e to your computer and use it in GitHub Desktop.
Save knolaust/49fab69c68ab810cad2b02ebc23db03e to your computer and use it in GitHub Desktop.
Update WordPress URLs in MySQL Database
<?php
/**
* Update URLs in the WordPress database when migrating from old URL to new URL.
*
* This function updates various tables and fields in the WordPress database to reflect the new URL
* when migrating a WordPress site.
*
* Usage:
* - Backup your WordPress database before running this function.
* - Call the function with the old URL and new URL as arguments to execute the updates.
*
* @param string $old_url The old URL to be replaced.
* @param string $new_url The new URL to replace the old URL.
*
* Gist Keywords: wordpress, database, url, db, migration
*
* @author Knol Aust
* @version 1.0.0
*/
// Only use temporarily. Call the function once and remove or comment out the knolaust_update_database_urls from functions.php
// You can always try oldurl.com and newurl.com.
// Example usage:
// knolaust_update_database_urls('https://www.oldurl.com', 'https://www.newurl.com');
function knolaust_update_database_urls($old_url, $new_url) {
global $wpdb;
// Update the home and siteurl options in wp_options table.
$sql1 = $wpdb->prepare(
"UPDATE $wpdb->options SET option_value = REPLACE(option_value, %s, %s) WHERE option_name = 'home' OR option_name = 'siteurl';",
$old_url,
$new_url
);
// Update the guid and post_content fields in wp_posts table.
$sql2 = $wpdb->prepare(
"UPDATE $wpdb->posts SET guid = REPLACE(guid, %s, %s);",
$old_url,
$new_url
);
$sql3 = $wpdb->prepare(
"UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s);",
$old_url,
$new_url
);
// Update the meta_value field in wp_postmeta table.
$sql4 = $wpdb->prepare(
"UPDATE $wpdb->postmeta SET meta_value = REPLACE(meta_value, %s, %s);",
$old_url,
$new_url
);
// Execute the SQL queries.
$wpdb->query($sql1);
$wpdb->query($sql2);
$wpdb->query($sql3);
$wpdb->query($sql4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment