I have a need to replace hostnames on certain external links. For example, I'd like to replace outbound links to http://www.example.com/whatever with http://staging.example.com/whatever throughout my site.

These links are all over the site, content, header, footer, menus, and so forth.

I have been doing this by using a general-purpose footer plugin to jam the following Javascript into all my site's HTML pages.

<script type="text/javascript">
  jQuery(document).ready(function () {
     jQuery("a[href^='http://www.example.com']").each(function() { 
      this.href = this.href.replace (

This works correctly. But it is a nasty hack.

My question is this: is there a better way to do this? Any advice?

  • Are the links in the post/page content or spread all over the site (sidebars, footer, etcetera)?
    – Luis Sanz
    May 24, 2016 at 18:29
  • You can try Database Search and Replace Script in PHP script or any of WordPress migration plugins to change URLs you need directly in the database. Any of these will change serialized values as well.
    – Max Yudin
    May 25, 2016 at 7:26

1 Answer 1


If the links are coming from the main content areas, you could create a hook which acts against this "content" output. In your themes functions.php file, you could try something like:

add_filter('the_content', 'the_url_filter_function_name', 30);
function the_url_filter_function_name($content) {
    return str_replace('bad-url.com', 'good-url.com', $content);

If the URLs you are looking to modify are being stored and output'd via different mechanisms, you will probably be able to locate hooks for them which could modify their content on-the-fly also. Abstracting this into an external configuration is another exercise in using config variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.