Replace WordPress Static URL’s with Dynamic URL’s

How can you stop WordPress from publishing static url’s to the database instead of using a dynamic url set from your website root? Often, when creating a test environment, WP developers will insert final content in the development server only to then realize the server address will change when published to the final, live site.

The url change is easily resolved by using the get_bloginfo(‘url’) variable throughout a theme, but content placed in the WordPress editor, such as links or images, will still link to the development server.

Here’s a quick fix that’ll remove the url from your posts, while replacing it with a root directory.

function thisismyurl_clean_static_url($content) {
	return str_replace('href="'.get_bloginfo('url'), 'href="', $content );
	return str_replace('src="'.get_bloginfo('url'), 'src="', $content );
}
add_filter('content_save_pre','thisismyurl_clean_static_url','99');
If you add this code snippet to your functions.php file, yourWordPress website will replace the existing URL with a single slash, indicating the root of your website. For example, http://thisismyurl.com/wordpress-development/ will become /wordpress-development/ in the hyperlinks href and img src attributes, which will both cut down on bandwidth and ensure the content is portable to another domain in the future.