Last active
January 2, 2016 18:29
-
-
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.
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
| 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