Skip to content

Instantly share code, notes, and snippets.

@fastmover
Last active January 2, 2016 18:29
Show Gist options
  • Select an option

  • Save fastmover/8344298 to your computer and use it in GitHub Desktop.

Select an option

Save fastmover/8344298 to your computer and use it in GitHub Desktop.
clean_absolute_urls() function searched the wp_posts table for references to the current hostname, and removes them making all urls relative instead of absolute. This is especially useful if migrating servers or urls.
function find_and_replace($needle, &$haystack) {
if(strpos($haystack, $needle) !== false) {
$haystack = preg_replace('|' . preg_quote($needle) . '|', '', $haystack);
}
}
/**
* This function makes relative urls from all absolute urls of the current domain.
*
*
* */
function clean_absolute_urls() {
global $wpdb;
$HOST_HTTP = 'http://' . $_SERVER['HTTP_HOST'];
$HOST_HTTPS = 'https://' . $_SERVER['HTTP_HOST'];
$failed = array();
$success = 0;
$posts = $wpdb->get_results("
SELECT * FROM `wp_posts` WHERE
`post_content` LIKE '%" . $HOST_HTTPS . "%' OR
`post_content` LIKE '%" . $HOST_HTTP . "%' OR
`post_excerpt` LIKE '%" . $HOST_HTTPS . "%' OR
`post_excerpt` LIKE '%" . $HOST_HTTP . "%' OR
`guid` LIKE '%" . $HOST_HTTPS . "%' OR
`guid` LIKE '%" . $HOST_HTTP . "%'
LIMIT 0,10000;
");
foreach($posts as $post) {
$content = $post->post_content;
$excerpt = $post->post_excerpt;
$guid = $post->guid;
find_and_replace($HOST_HTTP, $content);
find_and_replace($HOST_HTTPS, $content);
find_and_replace($HOST_HTTP, $excerpt);
find_and_replace($HOST_HTTPS, $excerpt);
find_and_replace($HOST_HTTP, $guid);
find_and_replace($HOST_HTTPS, $guid);
$post->post_content = $content;
$post->post_excerpt = $excerpt;
$post->guid = $guid;
$updatedID = wp_update_post($post);
if($updatedID == 0) {
$failed[] = $post->ID;
} else {
$success++;
}
}
return compact('failed', 'success');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment