Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example WordPress plugin to help simplify attachment URLs on multisite sites with mapped domains
<?php
/**
* Plugin Name: Multisite Domain Mapping Attachment URL Fixes
* Description: Update attachment URLs to use mapped domain and remove mention of "sites" path.
* Author: Chris Hardie
*
* Rewrite attachment URLs (and related srcset URLs) to the non-multisite, mapped domain version if a domain is mapped
* Requires that the related nginx config that maps the non-multisite URL to the multisite URL be in place
**/
add_filter( 'wp_get_attachment_url', 'jch_attachment_url_with_domain_mapping' );
function jch_attachment_url_with_domain_mapping( $attachment_url ) {
global $wpdb;
// Comes from https://wordpress.org/plugins/wordpress-mu-domain-mapping/
if ( function_exists( 'get_original_url' ) && function_exists( 'domain_mapping_siteurl' ) ) {
$orig_url = get_original_url( 'siteurl' );
$mapped_url = domain_mapping_siteurl( 'NA' );
if ( 'NA' !== $mapped_url ) {
if ( ! empty( $orig_url ) && ( $orig_url !== $mapped_url ) ) {
$attachment_url = str_replace( $orig_url, $mapped_url, $attachment_url );
}
$attachment_url = preg_replace( '!wp-content/uploads/sites/\d+/!', 'wp-content/uploads/', $attachment_url );
}
}
return $attachment_url;
}
add_filter( 'wp_calculate_image_srcset', 'jch_srscet_urls_with_domain_mapping' );
function jch_srscet_urls_with_domain_mapping( $sources ) {
if ( function_exists( 'domain_mapping_siteurl' ) ) {
$domain_mapped_url = domain_mapping_siteurl( 'NA' );
if ( 'NA' !== $domain_mapped_url ) {
foreach ( $sources as $source ) {
if ( ! empty( $source['url'] ) && ! empty( $source['value'] ) ) {
$sources[ $source[ 'value' ] ][ 'url' ] = preg_replace( '!wp-content/uploads/sites/\d+/!', 'wp-content/uploads/', $sources[ $source[ 'value' ] ][ 'url' ] );
}
}
}
}
return $sources;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.