Created
October 15, 2012 18:19
-
-
Save emersonbroga/3894127 to your computer and use it in GitHub Desktop.
Wp Update URL
This file contains hidden or 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
/* | |
* Wp Update URL | |
* Based on http://www.onextrapixel.com/2010/01/30/13-useful-wordpress-sql-queries-you-wish-you-knew-earlier/ | |
* Change the url on the database. | |
* @author Emerson Carvalho (@emersonbroga) | |
* | |
* @param $oldUrl STRING REQUIRED ex: http://www.site.com.br | |
* @param $newUrl STRING OPCIONAL ex: http://www.newsite.com | |
* | |
*/ | |
function wpUpdateUrl( $oldUrl, $newUrl = null ) | |
{ | |
global $wpdb; | |
if($newUrl === null){ | |
$newUrl = 'http'; | |
$newUrl.= (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? 's' : ''; | |
$newUrl.= '://'; | |
if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") { | |
$newUrl.= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"]; | |
} else { | |
$newUrl.= $_SERVER["SERVER_NAME"]; | |
} | |
} | |
if(!filter_var($oldUrl, FILTER_VALIDATE_URL) ) | |
throw new Exception('Old URL is not valid'); | |
if(!filter_var($newUrl, FILTER_VALIDATE_URL) ) | |
throw new Exception('New URL is not valid'); | |
$queries = array(); | |
$queries[] = sprintf("UPDATE wp_options SET option_value = replace(option_value, '%s', '%s') WHERE option_name = 'home' OR option_name = 'siteurl';", $oldUrl, $newUrl); | |
$queries[] = sprintf("UPDATE wp_posts SET guid = REPLACE (guid, '%s', '%s');", $oldUrl, $newUrl); | |
$queries[] = sprintf("UPDATE wp_posts SET post_content = REPLACE (post_content, '%s', '%s');", $oldUrl, $newUrl); | |
$queries[] = sprintf("UPDATE wp_posts SET post_content = REPLACE (post_content, 'src=\"%s', 'src=\"%s');", $oldUrl, $newUrl); | |
$queries[] = sprintf("UPDATE wp_posts SET guid = REPLACE (guid, '%s', '%s') WHERE post_type = 'attachment';", $oldUrl, $newUrl); | |
$queries[] = sprintf("UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, '%s','%s');", $oldUrl, $newUrl); | |
$errors = array(); | |
foreach($queries as $key => $sql){ | |
$result = $wpdb->query($sql); | |
if($result === false ) | |
$errors[] = $sql; | |
} | |
if(count($errors) > 0) | |
throw new Exception('Found errors on this queries:', join( PHP_EOL, $errors)); | |
else | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment