Fix Old Subsite URLs After Domain Mapping
Rewrites links and image URLs that still point at a site's old network address (like example.com/shop/) to its mapped domain when content is displayed.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
$wpide_old_urls = array( // Blog ID => old address (without trailing slash).
// 2 => 'https://network.example.com/shop',
);
$wpide_id = get_current_blog_id();
if ( empty( $wpide_old_urls[ $wpide_id ] ) ) {
return;
}
$wpide_old = untrailingslashit( $wpide_old_urls[ $wpide_id ] );
$wpide_new = untrailingslashit( home_url() );
if ( $wpide_old === $wpide_new ) {
return;
}
$wpide_fix = function ( $content ) use ( $wpide_old, $wpide_new ) {
if ( ! is_string( $content ) || false === strpos( $content, $wpide_old ) ) {
return $content;
}
$variants = array( $wpide_old, set_url_scheme( $wpide_old, 'http' ), str_replace( '/', '\/', $wpide_old ) );
return str_replace( $variants, array( $wpide_new, $wpide_new, str_replace( '/', '\/', $wpide_new ) ), $content );
};
foreach ( array( 'the_content', 'the_excerpt', 'widget_text', 'widget_block_content', 'wp_get_attachment_url' ) as $wpide_hook ) {
add_filter( $wpide_hook, $wpide_fix, 99 );
}
Notes
Set $wpide_old_urls per blog ID. This fixes display only; run a search-replace later to update the database permanently.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.