Skip to content

Instantly share code, notes, and snippets.

@cdekok
Last active August 29, 2015 14:24
Show Gist options
  • Save cdekok/b67895f7648404dc2778 to your computer and use it in GitHub Desktop.
Save cdekok/b67895f7648404dc2778 to your computer and use it in GitHub Desktop.
Change domain wp_options table in Wordpress
<?php
/**
* Script te replace domain in serialized arrays in Wordpress
* a simple sql replace is not enough :(
**/
if (PHP_SAPI !== 'cli') {
exit('CLI ONLY');
}
$hostname = 'something'; // normally localhost, but not necessarily.
$username = 'user'; // your db userid
$password = 'pass'; // your db password
$database = 'my_wp';
$db = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
foreach($db->query('SELECT * from wp_options') as $row) {
$value = @unserialize($row['option_value']);
if (!$value) {
continue;
}
if (is_string($value)) {
$value = replaceDomain($value);
}
else if (is_array($value)) {
array_walk($value, 'replaceDomainArray');
}
else {
// skip everything else
continue;
}
$value = serialize($value);
// query
$sql = "UPDATE `wp_options`
SET `option_value` = :option_value
WHERE `option_id` = :id";
$q = $db->prepare($sql);
$q->bindValue(':option_value', $value);
$q->bindValue(':id', $row['option_id'], PDO::PARAM_INT);
if (!$q->execute()) {
echo $q->errorCode().PHP_EOL;
print_r($q->errorInfo()).PHP_EOL;
var_export($row);
exit;
}
}
function replaceDomain($string) {
return str_replace('http://somedomain.bla/', 'http://new-domain.nl/', $string);
}
function replaceDomainArray(&$item,$key){
$item = replaceDomain($item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment